[英]C# How do I invoke an Action on a non-static member function?
I have the following code which works. 我有以下代码可行。 I pass in Actions which are just pointers to static memebers of this same class.
我传入的动作只是指向同一类静态成员的指针。 (Its purpose is to manage threading to safely access some COM objects on the rightly moded thread.)
(其目的是管理线程以安全地访问正确模式线程上的某些COM对象。)
But now I want to change DoCompute to non-static, and I want to Invoke func (also changed to non-static) with the same object that DoCompute has. 但是现在我想将DoCompute更改为非静态,并且我希望使用与DoCompute相同的对象来调用func(也更改为非静态)。
How do I get the static out, so there's passed-in data to work on? 如何获得静态输出,所以有传入的数据可以使用?
public static void DoCompute(Action func)
{
Type type = typeof(Computations);
AppDomain interopDomain = null;
if (thread != null)
thread.Join();
try
{
// Define thread.
thread = new System.Threading.Thread(() =>
{
// Thread specific try\catch.
try
{
// Create a custom AppDomain to do COM Interop.
string comp = "Computations";
interopDomain = AppDomain.CreateDomain(comp);
//// THIS LINE: What if func is a non-static member?
func.Invoke();
Console.WriteLine();
Console.WriteLine("End ");
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
});
// Important! Set thread apartment state to STA.
thread.SetApartmentState(System.Threading.ApartmentState.STA);
// Start the thread.
thread.Start();
// Wait for the thead to finish.
thread.Join();
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (interopDomain != null)
{
// Unload the Interop AppDomain. This will automatically free up any COM references.
AppDomain.Unload(interopDomain);
}
}
}
You just remove the static
keywords from both. 您只需从两者中删除
static
关键字。 Under the hood, when you pass an instance method into the Action
parameter, the instance is passed along as an invisible first parameter. 在引擎盖下,当您将实例方法传递给
Action
参数时,实例将作为不可见的第一个参数传递。 If you pass a static method into the Action
parameter, that does not happen. 如果将静态方法传递给
Action
参数,则不会发生这种情况。 The only thing you cannot do is pass a non-static method into the paramater from a static method. 你唯一不能做的是从静态方法将非静态方法传递给参数。
Perhaps this will be clearer with some code: 有些代码可能会更清楚:
public class TestClass
{
private string _text;
private void DoCompute(Action func)
{
func.Invoke();
}
private static void DoComputeStatic(Action func)
{
func.Invoke();
}
private static void StaticFunc()
{
Console.WriteLine("Static func");
}
private void NonstaticFunc()
{
Console.WriteLine(_text);
}
public void Run()
{
_text = "Nonstatic func";
DoCompute(NonstaticFunc);
DoComputeStatic(StaticFunc); //Can use static method - instance is ignored
}
public static void RunStatic()
{
DoComputeStatic(StaticFunc);
//DoCompute(NonstaticFunc); // Cannot use instance method - no instance
}
public void RunWithThread()
{
Thread thread = new Thread(() =>
{
_text = "Nonstatic func";
DoCompute(NonstaticFunc);
});
thread.Start();
thread.Join();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.