C# 嵌套类属性

标签 c#

在 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/

相关文章:

c# - 阅读中继器内的文本框

c# - .NET CORE 3 Windows 服务的基本路径返回 C :\Windows\System32, 但实际文件夹是 D:\MyCustomService

c# - 由于对象的当前状态,操作无效。使用 dotnet core 5 在 eventhub 中获取 microsoft.azure.amqp

c# - 如何在c#中反序列化Json文件以插入表中

c# - 执行 POST 时无法将 HttpWebRequest 超时设置为高于 100 秒?

c# - 在 C# 中交换 Powershell

c# - PInvoke c++ dll from c# - 尝试加载格式不正确的程序。 (来自 HRESULT : 0x8007000B) 的异常

c# - 是否可以从默认表 AspNetUsers 中删除行?如果是,请解释一下

c# - 从资源中加载嵌入的动画 Cursor

c# - 获取 DependencyProperties 源(绑定(bind)、const、...)并替换为包装器