Invoke调用中的匿名方法

时间:2008-10-31 10:49:09

标签: c# .net compiler-errors anonymous-methods

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

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

例如:

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

其中someParameter是此方法的本地

以上将导致编译器错误:

  

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

8 个答案:

答案 0 :(得分:214)

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

(请注意:如果使用捕获 async ,你需要保持谨慎,但同步是正常的 - 即上述情况很好)

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

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基类中。

答案 1 :(得分:43)

实际上您不需要使用delegate关键字。只需将lambda作为参数传递:

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

答案 2 :(得分:14)

myControl.Invoke(new MethodInvoker(delegate() {...}))

答案 3 :(得分:13)

您需要创建委托类型。匿名方法创建中的关键字“委托”有点误导。您不是创建匿名委托,而是匿名方法。您创建的方法可以在委托中使用。像这样:

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

答案 4 :(得分:6)

为了完整起见,这也可以通过Action方法/匿名方法组合来实现:

//Process is a method, invoked as a method group
Dispatcher.Current.BeginInvoke((Action) Process);
//or use an anonymous method
Dispatcher.Current.BeginInvoke((Action)delegate => {
  SomeFunc();
  SomeOtherFunc();
});

答案 5 :(得分:5)

我有其他建议的问题,因为我想有时从我的方法返回值。如果您尝试使用带有返回值的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;
        }));
    }

答案 6 :(得分:1)

我喜欢用Action代替MethodInvoker,它更短并且看起来更干净。

Invoke((Action)(() => {
    DoSomething();
}));

// OR

Invoke((Action)delegate {
    DoSomething();
});

例如

// Thread-safe update on a form control
public void DisplayResult(string text){
    if (txtResult.InvokeRequired){
        txtResult.Invoke((Action)delegate {
            DisplayResult(text);
        });
        return;
    }

    txtResult.Text += text + "\r\n";
}

答案 7 :(得分:0)

我从不明白为什么这会对编译器产生影响,但这足够了。

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

奖金:添加一些错误处理,因为如果从后台线程使用Control.Invoke,则可能会更新控件的文本/进度/启用状态,而不必关心控件已经被处置了。

public static class ControlExtensions
{
    public static void Invoke(this Control control, Action action)
    {
        try
        {
            if (!control.IsDisposed) control.Invoke(action);
        }
        catch (ObjectDisposedException) { }
    }
}