简体   繁体   English

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

[英]C# - automatic delegate type from method

Any way to avoid explicitly declaring MyMethodDelegate in a scenario like this? 有什么方法可以避免在这样的场景中明确声明MyMethodDelegate

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

BeginInvoke(new MyMethodDelegate(MyMethod), x);

I know about lambdas a-la ()=>MyMethod(x) , however I want to avoid them sometimes as they break edit-and-continue. 我知道lambdas a-la ()=>MyMethod(x) ,但是我想有时避免它们,因为它们会破坏编辑并继续。

Edit : just BeginInvoke(MyMethod, x) does not work: 编辑 :仅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 is defined as follows: BeginInvoke定义如下:

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

It does not specify any specific delegate type, so the compiler cannot detect which delegate type to instantiate from BeginInvoke(MyMethod. x) 它没有指定任何特定的委托类型,因此编译器无法检测从BeginInvoke(MyMethod. x)实例化哪个委托类型BeginInvoke(MyMethod. x)

For framework >= 3.5 you can use predefined delegates Action<> and Func<> (in your case) 对于framework> = 3.5,您可以使用预定义的委托Action <>和Func <>(在您的情况下)

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

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

You can often use the simplified version 您经常可以使用简化版

MyMethod

when a delegate is required. 当需要代表时 the keyword is often . 关键字经常是。

However if the compiler can't determine which type of delegate to convert the method group to you will have to help out with an explicit conversion 但是,如果编译器无法确定将方法组转换为哪种类型的委托,则必须帮助进行显式转换

Lambdas can come in handy when you wish to pass a function that you haven't already defined and don't need at other locations in the code. 当您希望传递一个尚未定义且在代码中的其他位置不需要的函数时,Lambdas可以派上用场。 Then Lambdas (and anonymous functions in general) will be very handy since you can then simply define the function at the spot where you need it. 然后,Lambda(通常是匿名函数)将非常方便,因为您可以在需要的地方简单地定义该函数。

in the case of BeginInvoke you are correct as noted in the comments that you can't you will need to explicitly convert the method group to a delegate either by casting or by assignment 在BeginInvoke的情况下,你是正确的,如注释中所述,你不能通过强制转换或赋值将方法组显式转换为委托

Func<int,bool) m = MyMethod;
BeginInvoke(m,x);
BeginInvoke((Func<inte,bool>)MyMethod,x);

will compile or you can pass in a lambda because that's interpreted as a Func 将编译或你可以传入一个lambda,因为它被解释为一个Func

BeginInvoke(a=>MyMethod(a),x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM