Why keyword 'this' cannot be used in a static method?

后端 未结 13 1842
遇见更好的自我
遇见更好的自我 2020-12-16 14:13

Why can\'t the keyword this be used in a static method? I am wondering why C# defines this constraint. What benefits can be gained by this constraint?

[

13条回答
  •  星月不相逢
    2020-12-16 14:40

    Another, more literal, take on your question:

    The 'this' keyword can't be used in a static method to avoid confusion with its usage in instance methods where it is the symbol to access the pointer (reference) to the instance passed automatically as a hidden parameter to the method.

    If not by that you could possibly define a local variable called 'this' in your static method, but that would be unrelated to the 'this' keyword referenced instance in the instance methods.

    Below is an example with two equivalent methods, one static the other an instance method. Both method calls will pass a single parameter to the methods executing code that will do the same thing (print the object's string representation on the console) and return.

    public class Someclass {
    
      void SomeInstanceMethod() 
        { System.Console.WriteLine(this.ToString()); }
    
      void static SomeStaticMethod(Someclass _this) 
        { System.Console.WriteLine(_this.ToString()); }
    
      public void static Main()
        {
           Someclass instance = new Someclass();
           instance.SomeInstanceMethod();
           SomeStaticMethod(instance);
        }
    }
    

提交回复
热议问题