Is `this` keyword optional when accessing members in C#?

前端 未结 4 631
梦毁少年i
梦毁少年i 2021-01-18 01:58

I notice that if you have a private member in a class, you can access it in the class methods by just referring to it\'s name. You do not need to say this.memberName

4条回答
  •  情话喂你
    2021-01-18 02:49

    "This" is almost always optional when you call members of current class.

    However, it is used for other purposes, e.g. to pass the current class instance as a parameter or to set a property,field or variable to the current instance.

    The only case where you must use it to call a method is when you call an extension method:

    class AClass {
        void CallIt() {
            Test();                     //not valid
            this.Test();                //valid 
        }
    }
    static class AnExtension {
        public static void Test(this AClass source) {
    
        }
    }
    

提交回复
热议问题