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

后端 未结 13 1878
遇见更好的自我
遇见更好的自我 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:33

    By static methods you can write:

    MyClass.static_method();
    

    which there is nothing to do with any object instance (so you don't need this keyword).

    Because static_method() works and doesn't need object instances for its job. static_method() doesn't know which object instance do you have, but it can change the behavior of all object instances:

    MyClass a = new MyClass();
    MyClass b = new MyClass();
    MyClass.static_method("PRINTER");
    a.display(); //print something
    b.display(); //print something
    MyClass.static_method("MONITOR");
    a.display(); //display something on monitor
    b.display(); //display something on monitor
    

    In this case, static_method() changes the behavior of display() method in all object instances of MyClass.

提交回复
热议问题