还有其他替代实施吗?
class Program
{
static void Main(string[] args)
{
var x = new Animal();
x.OnSpeak += (s, e) => Console.WriteLine("On Speak!");
x.OnSpeak += (s, e) => Console.WriteLine(e.Cancel ? "Cancel" : "Do not cancel");
Console.WriteLine("Before");
Console.WriteLine(string.Empty);
x.Speak(true);
x.Speak(false);
Console.WriteLine(string.Empty);
Console.WriteLine("After");
Console.Read();
}
public class Animal
{
public event CancelEventHandler OnSpeak;
public void Speak(bool cancel)
{
OnSpeak(this, new CancelEventArgs(cancel));
}
}
}
答案 0 :(得分:2)
这通常被称为"内联事件",并且只是在OnSpeak
事件触发时运行特定代码的另一种方式。
x.OnSpeak += (s, e) => Console.WriteLine("On Speak!");
s
是sender
,e
是事件参数。
您可以像这样重写代码,这可能更熟悉:
x.OnSpeak += OnSpeakEvent;
private static void OnSpeakEvent(object s, CancelEventArgs e)
{
Console.WriteLine("On Speak!");
}