简体   繁体   中英

C# - automatic delegate type from method

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

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.

Edit : just BeginInvoke(MyMethod, x) does not work:

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:

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)

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

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

Docs for 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. 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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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