调用调用中的匿名方法

在想要在Control.Invoke中匿名调用委托的语法上有麻烦。


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


例如:


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

其中someParameter在此方法本地


以上将导致编译器错误:


无法将匿名方法转换为类型“ System.Delegate”,因为它不是委托类型


杨__羊羊
浏览 525回答 3
3回答

慕田峪7331174

因为Invoke/ BeginInvoke接受Delegate(而不是类型的委托),所以您需要告诉编译器要创建什么类型的委托;MethodInvoker(2.0)或Action(3.5)是常见选择(请注意,它们具有相同的签名);像这样:control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});如果需要传递参数,则可以使用“捕获的变量”:string message = "Hi";control.Invoke((MethodInvoker) delegate {this.Text = message;});(注意:如果使用captures 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.0this.Invoke(() => { this.Text = "hi"; });当然,您可以使用BeginInvoke:public static void BeginInvoke(this Control control, Action action){    control.BeginInvoke((Delegate)action);}如果不能使用C#3.0,则可以使用常规实例方法(大概是在Form基类中)执行相同的操作。

千万里不及你

实际上,您不需要使用委托关键字。只需将lambda作为参数传递:control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));

翻阅古今

我对其他建议有疑问,因为我有时想从我的方法中返回值。如果您尝试将MethodInvoker与返回值一起使用,则似乎不喜欢它。所以我使用的解决方案是这样的(非常高兴听到一种使它更简洁的方法-我正在使用c#.net 2.0):    // Create delegates for the different return types needed.    private delegate void VoidDelegate();    private delegate Boolean ReturnBooleanDelegate();    private delegate Hashtable ReturnHashtableDelegate();    // Now use the delegates and the delegate() keyword to create     // an anonymous method as required    // Here a case where there's no value returned:    public void SetTitle(string title)    {        myWindow.Invoke(new VoidDelegate(delegate()        {            myWindow.Text = title;        }));    }    // Here's an example of a value being returned    public Hashtable CurrentlyLoadedDocs()    {        return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()        {            return myWindow.CurrentlyLoadedDocs;        }));    }
打开App,查看更多内容
随时随地看视频慕课网APP