当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net - 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 Me");

}

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?

网友答案:
PrintMe c = HelpMe;
网友答案:

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

(3)
PrintMe c = HelpMe;

i.e. without parenthesis

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: