简体   繁体   English

嵌套类:无法访问静态上下文中的非静态字段

[英]Nested class: Cannot access non-static field in static context

I have a class C with some internal variables.我有一个带有一些内部变量的 C 类。 It has a nested class N that wants to access the variables in C. Neither C nor N are static, although C has some static methods and variables.它有一个嵌套类 N 想要访问 C 中的变量。 C 和 N 都不是静态的,尽管 C 有一些静态方法和变量。 When I try to access a non-static variable in C from NI get the squiggly underline and the message "Cannot access non-static field [fieldname] in static context".当我尝试从 NI 访问 C 中的非静态变量时,得到波浪形下划线和消息“无法在静态上下文中访问非静态字段 [字段名]”。

This seems to have something to do with the nested class, since I can access the variable fine from the enclosing class itself.这似乎与嵌套类有关,因为我可以从封闭类本身访问该变量。

ReSharper suggests I make _t static but that isn't an option. ReSharper 建议我将 _t 设为静态,但这不是一个选项。 How do I deal with this?我该如何处理?

public sealed partial class C
{
    string _t;

    class N
    {
        void m()
        {
            _t = "fie"; // Error occurs here
        }
    }
}

This isn't Java, and you don't have inner classes.这不是 Java,并且您没有内部类。

An instance of a nested class is not associated with any instance of the outer class, unless you make an association by storing a reference (aka handle/pointer) inside the constructor.嵌套类的实例不与外部类的任何实例相关联,除非您通过在构造函数中存储引用(也称为句柄/指针)来建立关联。

public sealed partial class C
{
    string _t;

    class N
    {
        readonly C outer;

        public N(C parent) { outer = parent; }

        void m()
        {
            outer._t = "fie"; // Error is gone
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM