C# - automatic delegate type from method

家住魔仙堡 提交于 2019-12-22 10:27:50

问题


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)


回答1:


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




回答2:


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);


来源:https://stackoverflow.com/questions/13760744/c-sharp-automatic-delegate-type-from-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!