Why can't you use the keyword 'this' in a static method in .Net?

后端 未结 7 1560
温柔的废话
温柔的废话 2020-11-27 06:46

I\'m trying to use the this keyword in a static method, but the compiler won\'t allow me to use it.

Why not?

相关标签:
7条回答
  • 2020-11-27 06:53

    For OP's question, refer to the accepted answer. This answer is for the ones who're looking for a fast one liner to use in static methods.

    If the class is a form, and it's open (you need the name of the form as well), this can be called within a static method;

    Application.OpenForms["MainForm"];
    
    0 讨论(0)
  • 2020-11-27 06:55

    That's an easy one. The keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class. There is a much more in depth explanation of what static members are and why/when to use them in the MSDN docs.

    0 讨论(0)
  • 2020-11-27 07:00

    As an additional note, from a Static method, you can access or static members of that class. Making the example below valid and at times quite useful.

    public static void StaticMethod(Object o)
    {
         MyClass.StaticProperty = o;
    }
    
    0 讨论(0)
  • 2020-11-27 07:05

    If You want to use non static function of class in static function.Create object of class in static function. For Eg

        Class ClsProgram(){
    public static void staticfunc(){
    ClsProgram Obj = new ClsPrograM()
    Obj.NonStaticFunc();
    }
    public void NonStaticFunc(){}
    }
    
    0 讨论(0)
  • 2020-11-27 07:11

    this represents the current instance object and there is no instance with static methods.

    0 讨论(0)
  • 2020-11-27 07:15

    Static methods are Class specific and not instance specific. "this" represents an instance of the class at runtime, so this can't be used in a static context because it won't be referencing any instance. Instead the class's name should be used and you would only be able to access static members in the class

    0 讨论(0)
提交回复
热议问题