gpt4 book ai didi

C# 如何在非静态成员函数上调用 Action?

转载 作者:行者123 更新时间:2023-11-30 16:56:12 27 4
gpt4 key购买 nike

我有以下有效的代码。我传入的 Actions 只是指向同一类的静态成员的指针。 (其目的是管理线程以在正确模式的线程上安全地访问某些 COM 对象。)

但现在我想将 DoCompute 更改为非静态的,并且我想使用与 DoCompute 相同的对象调用 func(也更改为非静态的)。

如何去除静电,以便处理传入的数据?

 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);
}
}
}

最佳答案

您只需从两者中删除 static 关键字。在幕后,当您将实例方法传递给 Action 参数时,该实例将作为不可见的第一个参数传递。如果将静态方法传递给 Action 参数,则不会发生这种情况。您唯一不能做的就是将非静态方法从静态方法传递到参数中。

也许用一些代码会更清楚:

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();
}
}

关于C# 如何在非静态成员函数上调用 Action?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com