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

前端 未结 1 1621
天涯浪人
天涯浪人 2020-12-19 05:39

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 method

相关标签:
1条回答
  • 2020-12-19 06:07

    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
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题