开发者

Delegate Instantiation -Clarification

When i have delegate like

public delegate void PrintMe();

(1)
PrintMe a = delegate() { MessageBox.Show("Hello"); };
a();

(2)
PrintMe b = () => { MessageBox.Show("Hello"); };
b();

(3)
PrintMe c = new PrintMe(HelpMe);
c();

static void HelpMe()
{
   MessageBox.Show("Help M开发者_如何学Ce");
}

for (1) and (2) I did not instatntiate the delegate it is directly pointing to anonymous methods.But as in the case of (3) I need to instatntiate the delegate and pass the static method.for case (3) can't i declare like PrintMe c= HelpMe(); ?.How does (1) and (2) work?


Thanks to the implicit conversion between method groups and delegates you can say

(3)
PrintMe c = HelpMe;

i.e. without parenthesis


PrintMe c = HelpMe;


In (1) and (2) the compiler implicitly converts your lambda expression into a delegate.

If you try to do

PrintMe c= HelpMe();

then you are telling the compiler to generate a call to HelpMe and assign the result of that call to c. Instead, you can do

PrintMe c = HelpMe;

Here, HelpMe occours as what is known as a method group (it is not just a method, because it may have overloads), which may be converted to a delegate if at least one method in the group fits the delegate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜