Why can't you call a non-static method from a static method?

后端 未结 9 396
北海茫月
北海茫月 2020-12-03 19:32

I have a static method [Method1] in my class, which calls another method [Method2] in the same class and is not a static method. But this is a no-no. I get this error:

相关标签:
9条回答
  • 2020-12-03 20:08

    You need an instance of the class class to call the non-static method. You could create an instance of ClassName and call Method2 like so:

    public class ClassName
    {
        public static void Method1()
        {
            ClassName c = new ClassName();
            c.Method2();
        }
    
        public void Method2()
        {
            //dostuff
        }
    }
    

    The static keyword basically marks a method as being call-able by referencing only its type [ClassName]. All non-static methods have to be referenced via an instance of the object.

    0 讨论(0)
  • 2020-12-03 20:08

    The static method by definition is not provided access to a this. Hence, it cannot call a member method.

    If the member method you're trying to call from the static method doesn't need a this, you can change it into a static method.

    0 讨论(0)
  • 2020-12-03 20:09

    Because a "static" method is what's known as a "class method". That is, you dispatch on an object one of two ways in a class-based language like C#, by class or by instance. non-static members can be dispatched to by other non-static members, conversely, static members can be called only be other static members.

    Keep in mind, you can get to one from the other, by the "new" mechanism, or visa versa.

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