在 C# 中,为什么嵌套类必须实例化其父类,才能在代码中引用其父类非静态属性?
public class OuterClass
{
public int OuterClassProperty
{
get
{
return 1;
}
}
public class InnerClass
{
public int InnerClassProperty
{
get
{
/* syntax error: cannot access a non-static
* member of outer type via nested type.
*/
return OuterClassProperty;
}
}
}
}
看来我必须这样做:
public class OuterClass
{
public int OuterClassProperty
{
get
{
return 1;
}
}
public class InnerClass
{
public int InnerClassProperty
{
get
{
OuterClass ImplementedOuterClass = new OuterClass();
return ImplementedOuterClass.OuterClassProperty;
}
}
}
}
我认为第一个代码示例应该没问题,因为如果实例化 InnerClass
,则父类将首先实现 - 以及父类属性。
感谢您的帮助,我正在尝试学习 C# 的细节...而且我对 Java 不熟悉,与 Java 相比没有多大帮助...
最佳答案
您所观察到的行为已在 C# 规范中明确说明。下面是 C# 5.0 的片段:
10.3.8.4 this access
A nested type and its containing type do not have a special relationship with regard to this-access (§7.6.7). Specifically, this within a nested type cannot be used to refer to instance members of the containing type. In cases where a nested type needs access to the instance members of its containing type, access can be provided by providing the this for the instance of the containing type as a constructor argument for the nested type.
C# 中嵌套类的行为与其他语言不同,例如 Java inner classes in c#和C+因为C#是不同语言设计团队创建的不同语言。选择特定行为的确切历史原因可以在 C# 设计团队成员的博客、.Net 设计指南书籍或 MSDN 文章中找到。
关于C# 嵌套类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29854470/