简体   繁体   English

使用匿名方法订阅事件

[英]Subscribing to events using anonymous methods

I am having problems understanding how the below works (questions below code): 我在理解以下内容的工作方式时遇到问题(代码下方的问题):

private delegate void MyDelegate(int i);
private event MyDelegate myEvent;

public void EventTests() {
    //Option One
    myEvent += One;

    //Option Two
    myEvent += delegate{ Two(true); };

    //Option Three
    myEvent += () => { Two(true); };
}

private void One(int i) { }

private void Two(bool j) { }

Questions: 问题:

  1. I can understand why Option One works, as the event myEvent expects a delegate with an int parameter to be attached to it. 我可以理解为什么选项一有效,因为事件myEvent希望将带有int参数的委托附加到该选项。 Why does Option Two work though? 为什么选项二有效? it is attaching an anonymous method with incorrect signature to the event, no? 它将带有错误签名的匿名方法附加到事件,不是吗?

  2. So if Option Two works, why does option Three not work? 因此,如果选项二有效,为什么选项三不起作用? It seems that the signature needs to be (int i) => { Two(true); }; 似乎签名需要是(int i) => { Two(true); }; (int i) => { Two(true); }; as opposed to () as written above. 与上述的()相反。 But Option Two worked without the right signature, so why does this anonymous method cause an error? 但是选项二在没有正确签名的情况下工作,那么为什么这个匿名方法会导致错误?

Thanks a lot. 非常感谢。

Option two works because the compiler automatically figures out what the function signature is when the parameter list is omitted. 选项二之所以起作用,是因为当省略参数列表时,编译器会自动找出函数签名是什么。 Once you add the () to the delegate keyword, you've defined a specific parameter list of none and the compiler throws a fit. ()添加到委托关键字后,就定义了一个特定的参数列表,其中没有一个,编译器将进行拟合。

Option three is a lambda expression with an incorrect parameter list defined. 选项三是一个lambda表达式,其中定义了错误的参数列表。

Microsoft's C# Programming Guide states: Microsoft的C#编程指南指出:

There is one case in which an anonymous method provides functionality not found in lambda expressions. 在一种情况下,匿名方法提供了lambda表达式中找不到的功能。 Anonymous methods enable you to omit the parameter list. 匿名方法使您可以省略参数列表。 This means that an anonymous method can be converted to delegates with a variety of signatures. 这意味着可以将匿名方法转换为具有各种签名的委托。 This is not possible with lambda expressions. 对于lambda表达式,这是不可能的。

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

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