是否有可能调用在C#中的静态函数内部的非静态函数吗?
问题描述:
是否有可能调用在C#中使用静态函数内的公共非静态类的非静态函数吗?
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.
任何想法?
答
这听起来像你想数据传递到您的线程。试试这个:
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();
}
}