C# - 方法的自动委托类型

Iva*_*kov 3 c# methods delegates invoke

有什么方法可以避免MyMethodDelegate在这样的场景中明确声明?

bool MyMethod(string x)
{
    //...
}

BeginInvoke(new MyMethodDelegate(MyMethod), x);
Run Code Online (Sandbox Code Playgroud)

我知道 lambdas a-la ()=>MyMethod(x),但是有时我想避免它们,因为它们会破坏编辑并继续。

编辑:只是BeginInvoke(MyMethod, x)不起作用:

The best overloaded method match for 'System.Windows.Forms.Control.BeginInvoke(System.Delegate, params object[])' has some invalid arguments
Argument 1: cannot convert from 'method group' to 'System.Delegate'
Argument 2: cannot convert from 'string' to 'object[]'
Run Code Online (Sandbox Code Playgroud)

BeginInvoke 定义如下:

public IAsyncResult BeginInvoke(Delegate method, params object[] args);
Run Code Online (Sandbox Code Playgroud)

它没有指定任何特定的委托类型,因此编译器无法检测从哪个委托类型实例化 BeginInvoke(MyMethod. x)

小智 5

对于框架 >= 3.5,您可以使用预定义的委托 Action<> 和 Func<>(在您的情况下)

    BeginInvoke(new Func<int, bool>(MyMethod), x);
Run Code Online (Sandbox Code Playgroud)

Func 的文档 http://msdn.microsoft.com/ru-ru/library/bb549151.aspx