可空枚举不包含错误

Nullable enums does not contain error

我想将我的枚举创建为可为 null,而不是添加默认值为 0 的默认条目。

但是,在以下情况下,我遇到了语法错误,我现在无法理解原因或如何修复它。这可能是简单的事情,但最简单的事情...

这是我的 decare enums 为 nullable 的属性:

public Gender? Gender { get; private set; }

public MaritalStatus? MaritalStatus { get; private set; }

这是一个给我语法错误的方法,即 Gender does not contain..., MaritalStatus does not contain...:[=​​12=]

    string GetTitle()
    {
        if (Gender == null || MaritalStatus == null)
            return null;
        if (Gender == Gender.M) // Error here!
            return "Mr";
        else if (
            MaritalStatus == MaritalStatus.Married ||
            MaritalStatus == MaritalStatus.Separated ||
            MaritalStatus == MaritalStatus.Widowed) // Error here!
            return "Mrs";
        else
            return "Ms";
    }

感谢任何建议。

您有枚举 MaritalStatusGender。同时,您还拥有名为 MaritalStatusGender 的属性。你需要避免这种情况。

此处:

if (Gender == Gender.M)
if (MaritalStatus == MaritalStatus.Married)

语法不正确,因为 GenderMaritalStatus 被识别为变量,而不是类型。
此外,您需要使用 .Value 来访问 Nullable.

的值

因此,您可以显式指定命名空间:

if (Gender.Value == YourNamespace.Gender.M)
if (MaritalStatus.Value == YourNamespace.MaritalStatus.Married)

但我强烈建议将您的枚举重命名为 GenderEnumMaritalStatusEnum

为什么会这样?

这个问题在这里很容易重现:

enum SameName { Value }
class Tester
{
   void Method1() {
      SameName SameName;
      SameName test = SameName.Value; // Works!
   }
   void Method2() {
      string SameName;
      SameName test = SameName.Value; // Doesn't work! Expects string method Value
   }
}

Eric Lippert 在 this answer 中描述了这样做的原因:

C# was designed to be robust in the face of a property named the same as its type because this is common:

class Shape
{
    public Color Color { get; set; }
    ...

If you have a type Color, it is very common to have a property also called Color, and there's no good way to rename either of them. Therefore C# was designed to handle this situation reasonably elegantly.

所以,如果你的变量是Enum类型,那么它指的是枚举成员; else - 它指的是变量。 Enum? 属于 "else".