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

后端 未结 9 503
北海茫月
北海茫月 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.

提交回复
热议问题