Is there a way to call a non-static method from a static method?

十年热恋 提交于 2020-01-12 08:58:08

问题


Here's what I have.

public static void Person_home_phone_TextChanged(object sender, EventArgs e) { ... }

Is there any way to access non-static methods from the same or another class from inside this static method?

I need grab the text in the Person_home_phone text box and save it to a class data member.


回答1:


Example() -> Example

You would just need to create an instance of the type then call the non-static, from a static method.

public class Example(){

    public static void StaticExample()
    {

        Example example = new Example();
        example.NonStatic();
    }

    public void NonStatic()
    {

    }

}



回答2:


You need to have a instance of the class to call a non-static method.




回答3:


Solution #1: Instantiate a new instance of Car every time the method is called.

 public static void DoSomething()
        {
            Car c = new Car();
            c.NonStaticMethod();
        }

Solution #2: Pass a Car to the method.

 public static void DoSomething(Car c)
        {
            c.NonStaticMethod();
        }

Solution #3:

Use a singleton Car to support the static method. (If calls from multiple threads are a possibility, you might also need locking. Note that System.Windows.Forms.Timer does not introduce a thread.)

 public class Car
    {
        private static Car m_Singleton = new Car();

        public static void DoSomething()
        {
            m_Singleton.NonStaticMethod();
        } 

Note that you have not explained your memory problems with Timer. It is very possible that there is a solution to that underlying problem.




回答4:


Instance methods (vel. non-static) can only be called in context of an instance of that class. So you can call it, but you have to have an object of that class available somewhere in your static method.




回答5:


A non-static method requires an instance of the class. Unless you have passed in an instance, or created an instance in your method, you cannot call a non-static method, as you have no idea what instance of the class that method should operate on.

You need an instance of the class class to call the non-static method.




回答6:


You should have an object to access its method.

statics doesn't belong to objects. They belongs to class declarations.



来源:https://stackoverflow.com/questions/15905248/is-there-a-way-to-call-a-non-static-method-from-a-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!