Is it possible to call a non-static function insid

2019-02-19 07:39发布

Is it possible to call a non-static function that uses a public non-static class inside a static function in C#?

public class MyProgram
{
    private Thread thd = new Thread(myStaticFunction);
    public AnotherClass myAnotherClass = new AnotherClass();

    public MyProgram()
    {
        thd.Start();
    }

    public static void myStaticFunction()
    {
        myNonStaticFunction();
    }

    private void myNonStaticFunction()
    {
        myAnotherClass.DoSomethingGood();
    }
}

Well, the invalid code like above is what I need.

Any idea?

标签: c# static
5条回答
我只想做你的唯一
2楼-- · 2019-02-19 08:11

It sounds like you want to pass data to your thread. Try this:

public class MyProgram
{
    private Thread thd;
    public AnotherClass myAnotherClass = new AnotherClass();

    public MyProgram()
    {
        thd = new Thread(() => myStaticFunction(this));
        thd.Start();
    }

    public static void myStaticFunction(MyProgram instance)
    {
        instance.myNonStaticFunction();
    }

    private void myNonStaticFunction()
    {
        myAnotherClass.DoSomethingGood();
    }
}
查看更多
小情绪 Triste *
3楼-- · 2019-02-19 08:16

Not directly no. You must have an instance of Program in order to call the non-static method. For example

public static void MyStaticFunc(Program p) {
  p.myNonStaticFunction();
}
查看更多
Ridiculous、
4楼-- · 2019-02-19 08:16

If the myAnotherClass variable is declared as static, then yes, you can call methods on it.

That's not quite the answer to the question you asked, but it will allow you to call the method in the way you wantt to.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-02-19 08:19

No.

Non-static functions, by definition, require a class instance. If you create an instance of your class within the static function, or have a static Instance property in your class, you can via that object reference.

查看更多
爷的心禁止访问
6楼-- · 2019-02-19 08:23

To call a non static function you need to have an instance of the class the function belongs to, seems like you need to rethink why you need a static function to call a non static one. Maybe you're looking for the Singleton pattern ?

Or maybe you should just pass in a non-static function to new Thread()

查看更多
登录 后发表回答