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

后端 未结 9 478
北海茫月
北海茫月 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:06

    First you need to create instance of the class in order to call non-static method or functions.

    public class ClassHelper()
    {
       public static ClassHelper GetInstance()
        {
            ClassHelper instance = null;
    
            if (System.Web.HttpContext.Current == null)
            {
                instance = new ClassHelper();
                return instance;
            }
    
            if (System.Web.HttpContext.Current.Application["CLASSHELPER_INSTANCE"] == null)
            {
                instance = new ClassHelper();
                System.Web.HttpContext.Current.Application["CLASSHELPER_INSTANCE"] = instance;
            }
    
            instance = (ClassHelper)System.Web.HttpContext.Current.Application["CLASSHELPER_INSTANCE"];
    
            return instance;
        }
    
    
       public string Test()
       {
           return "test123";
       }
    
    }
    

    Then you can call the function as follows:

    textBox1.Text = ClassHelper.GetInstance().Test();
    

提交回复
热议问题