Handling delegate with out parameter
我有一个委托和带有out参数的事件:
public delegate void ExampleDelegate(object sender, EventArgs e, out string value);
public event ExampleDelegate Example;
当我试图处理事件时:
1 2 3 4 | mg.Example += (sender, e, val) => { //do stuff }; |
我得到的错误参数3必须用"out"关键字声明
当我输入建议的out关键字时,就像这样:
1 2 3 4 | mg.Example += (sender, e, out val) => { //do stuff }; |
我得到了一个额外的错误:找不到名称空间名称"val"的类型等。
我做错什么了?
好吧,正如它在这里明确指出的,您需要指定
1 | (sender, e, out string val)=> ... |
您的事件处理程序不符合.NET准则。
如果必须这样使用它,请使用委托,而不是事件。
如果有两个事件处理程序修改out参数,则会遇到问题。
参考:事件教程
.NET Framework Guidelines
Although the C# language allows events to use any delegate type, the
.NET Framework has some stricter guidelines on the delegate types that
should be used for events. If you intend for your component to be used
with the .NET Framework, you probably will want to follow these
guidelines.The .NET Framework guidelines indicate that the delegate type used for
an event should take two parameters, an"object source" parameter
indicating the source of the event, and an"e" parameter that
encapsulates any additional information about the event. The type of
the"e" parameter should derive from the EventArgs class. For events
that do not use any additional information, the .NET Framework has
already defined an appropriate delegate type: EventHandler.
ZMBQ已经给出了如何更正错误的答案。
我添加这个只是为了完整性。