简体   繁体   中英

Using “this” with a class name in C#

[Edit] What I wanted to ask was just putting a class name with this , so it wasn't about referencing an outer class member. Sorry for my inappropriate example!

[Edit2] Someone reported this as a duplicate BUT NOT! As I said earlier, I just wanted to know if it's possible to reference MyClass.this and this interchangeably like in Java. This wasn't a practical question at all but just for learning C# language itself. I don't mind removing this if people really think it's a duplicate so let me know.

In Java, you can use this with class names like this:

class OuterClass {
    int outerMember = 1;

    class InnerClass {
        int innerMember = 2;

        public void printOuterMember() {
            System.out.println(OuterClass.this.outerMember);
            System.out.println(outerMember);
        }

        public void printInnerMember() {
            System.out.println(InnerClass.this.innerMember);
            System.out.println(this.innerMember);
            System.out.println(innerMember);
        }
    }
}

Sometimes class names are not needed, but sometimes helpful.

So I tried the same thing in C# but it seems it's impossible. Am I right?

C# does not support this, in Java the nested class captures the parent object reference. C# nested classes are more like static nested classes in Java. If you want access to the parent class you will need to pass a reference to it in the nested class constructor.

Nested classes will have access to private fields of the parent class if they have a reference to it, so you can achieve similar results, just the access to the parent class instance is not automatic as it is in Java. So this code works

class Owner
{
    private int field;
    class Nested
    {
        public Nested(Owner owner) { this.owner = owner; }
        Owner owner;
        public int D()
        {
            return owner.field;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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