How to access to the Outer class's field from Inner class of same name in C#? (nested-class)

StackOverflow https://stackoverflow.com/questions/19480793

  •  01-07-2022
  •  | 
  •  

문제

How can I access to the field of outer class from inner class if the name of parameter is same as the outer class's field name?

For example -

class OuterClass
{
    static int Number;

    class InnerClass
    {
        public InnerClass(int Number)
        {
            Number = Number;   // This is not correct
        }
    }
}

So I tried like below -

class OuterClass
{
    static int Number;

    class InnerClass
    {
        public InnerClass(int Number)
        {
            this.this.Number = Number;   // Gives compiler error
        }
    }
}

How can I access it, please help ...

Thanks.

도움이 되었습니까?

해결책

you are looking for

class OuterClass
{
    static int Number;

    class InnerClass
    {
        public InnerClass(int Number)
        {
            OuterClass.Number = Number;   
        }
    }
}

다른 팁

Since it is static, you can just access it by writing: OuterClass.Number = Number;

You can do something in the lines of this:

Public InnerClass
{
    private MainClass _mainclass;

    public InnerClass(MainClass mainclass)
    {
         this._mainclass = mainclass;
    }


}

This way, you always create the inner class with a reference to the parent class and can call it with mainclass.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top