本文介绍了C# - 自动委托类型从方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何方式避免在这种情况下明确声明 MyMethodDelegate

Any way to avoid explicitly declaring MyMethodDelegate in a scenario like this?

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

BeginInvoke(new MyMethodDelegate(MyMethod), x);

我知道lambdas a-la ()=> MyMethod(x ),但是我想避免这些错误,因为它们会打破编辑和继续。

I know about lambdas a-la ()=>MyMethod(x), however I want to avoid them sometimes as they break edit-and-continue.

编辑 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[]'

BeginInvoke定义为如下:

BeginInvoke is defined as follows:

public IAsyncResult BeginInvoke(Delegate method, params object[] args);

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

It does not specify any specific delegate type, so the compiler cannot detect which delegate type to instantiate from BeginInvoke(MyMethod. x)

推荐答案

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

For framework >= 3.5 you can use predefined delegates Action<> and Func<> (in your case)

    BeginInvoke(new Func<int, bool>(MyMethod), x);

文件为Func

这篇关于C# - 自动委托类型从方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 08:34