为什么使此 getter 可为空会导致编译错误?

Why does making this getter nullable cause a compile error?

此代码有效:

class Example
{
    public Int32 Int32
    {
        get { return Int32.Parse("3"); }
    }
}

此代码无法编译:

class Example
{
    public Int32? Int32
    {
        get { return Int32.Parse("3"); }
    }
}

CS1061 'int?' does not contain a definition for 'Parse' and no extension method 'Parse' accepting a first argument of type 'int?' could be found (are you missing a using directive or an assembly reference?)


我的例子可能看起来很傻,但如果你使用想象一个枚举,它会更有意义,比如

public Choice? Choice { get { return Choice.One; } }

在第二个例子中,Int32 指的是 属性 Int32 而不是键入 System.Int32。由于 属性 Int32System.Nullable(System.Int32) 类型,它没有解析方法。

你必须写,

public Int32? Int32
{
    get { return System.Int32.Parse("3"); }
}

有属性类型名称与属性名称相同的特殊情况是说明:

7.6.4.1 Identical simple names and type names
In a member access of the form E.I, if E is a single identifier, and if the meaning of E as a simple-name (§7.6.2) is a constant, field, property, local variable, or parameter with the same type as the meaning of E as a type-name (§3.8), then both possible meanings of E are permitted. The two possible meanings of E.I are never ambiguous, since I must necessarily be a member of the type E in both cases. In other words, the rule simply permits access to the static members and nested types of E where a compile-time error would otherwise have occurred.

因此,在您的第一个代码段中,简单名称 Int32 允许引用 属性 Int32 以及键入 Int32.

在不应用规则的第二个片段中,简单名称 Int32 仅引用 属性。