gpt4 book ai didi

c# - Invoke调用中的匿名方法

转载 作者:IT王子 更新时间:2023-10-29 03:33:24 25 4
gpt4 key购买 nike

我们想在 Control.Invoke 中匿名调用委托(delegate)的语法有点问题。

我们尝试了多种不同的方法,但都无济于事。

例如:

myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); }); 

其中 someParameter 是该方法的局部参数

以上会导致编译错误:

Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

最佳答案

因为 Invoke/BeginInvoke 接受 Delegate(而不是类型化委托(delegate)),您需要告诉编译器要创建什么类型的委托(delegate); MethodInvoker (2.0) 或 Action (3.5) 是常见的选择(注意它们具有相同的签名);像这样:

control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});

如果需要传入参数,那么“捕获变量”就是这种方式:

string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});

(警告:如果使用捕获async,您需要谨慎一些,但sync 没问题 - 即上面的没问题)

另一种选择是编写扩展方法:

public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate)action);
}

然后:

this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });

你当然可以用 BeginInvoke 做同样的事情:

public static void BeginInvoke(this Control control, Action action)
{
control.BeginInvoke((Delegate)action);
}

如果您不能使用 C# 3.0,您可以使用常规实例方法执行相同操作,大概在 Form 基类中。

关于c# - Invoke调用中的匿名方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/253138/

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