Jos*_*osh 22
因为事件可以由多个侦听器处理.事件处理程序没有保证顺序(虽然我认为它们是按照现实订阅的顺序调用的.)
相反,对于想要"返回"某些数据的事件,约定是具有可变的EventArgs对象,例如CancelEventArgs,其Cancel属性可以设置为true.这比返回值的优点是链中的事件处理程序可以查看属性以查看是否已经设置了另一个处理程序.但是你仍然会遇到设置财产的最后一个获胜的情况.
如果它是一个返回值,整个概念将会复杂得多.
实际上,事件可以有返回值; 简单地说,这不是一个好主意,因为当可能有多个侦听器时需要更复杂的处理...更常见的是,可能有一个可设置的属性和一个EventArgs
子类.
但这是一个使用事件返回值的示例; 这通常不是一个好主意; 仅供参考:
using System;
delegate int SomeBizarreEvent(object sender); // non-standard signature
class Foo {
public event SomeBizarreEvent Bizarro;
public void TestOverall() {
SomeBizarreEvent handler = Bizarro;
if (handler != null) {
Console.WriteLine(handler(this));
}
}
public void TestIndividual() {
SomeBizarreEvent handler = Bizarro;
if (handler != null) {
foreach (SomeBizarreEvent child in handler.GetInvocationList()) {
Console.WriteLine(child(this));
}
}
}
}
class Program {
static void Main() {
Foo foo = new Foo();
foo.Bizarro += delegate { return 1; };
foo.Bizarro += delegate { return 5; };
// writes 5 (the last result wins)
foo.TestOverall();
// writes 1, 5
foo.TestIndividual();
}
}
Run Code Online (Sandbox Code Playgroud)