Can i access outer class objects in inner class [duplicate]

我的未来我决定 提交于 2019-11-29 03:08:32
Andrew Anderson

If I'm reading you correctly you want to access the objB property of class A within innerC WITHOUT passing it along.

This isn't how C# inner classes work, as described in this article: C# nested classes are like C++ nested classes, not Java inner classes

If you want to access A.objB from innerC then you are going to have to somehow pass class A to innerC.

dlras2

You need to pass a reference of OuterClass to InnerClass, perhaps in the constructor, like:

public class OuterClass
{
    //OuterClass methods

    public class InnerClass
    {
        private OuterClass _outer;

        public InnerClass(OuterClass outer)
        {
            _outer = outer;
        }
    }
}

Then you can use that reference in all of your InnerClass methods.

Since your class B is within the same scope as class C, that is, within class A, you will be able to instantiate the nested type B from nested type C and use it.

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