Nested class: Cannot access non-static field in static context

社会主义新天地 提交于 2019-12-18 05:56:33

问题


I have a class C with some internal variables. 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. When I try to access a non-static variable in C from N I get the squiggly underline and the message "Cannot access non-static field [fieldname] in static context".

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. How do I deal with this?

public sealed partial class C
{
    string _t;

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

回答1:


This isn't Java, and you don't have inner classes.

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
        }
    }
}


来源:https://stackoverflow.com/questions/10988878/nested-class-cannot-access-non-static-field-in-static-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!