“x.OnSpeak + =(s,e)”是什么意思?

时间:2014-12-27 13:57:45

标签: c# events

  • 我知道这是事件args的“e”,但是“s”在这里是什么意思和“+ =(,)=>” ?
  • 还有其他替代实施吗?

    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));
       }
     }
    }
    

1 个答案:

答案 0 :(得分:2)

这通常被称为"内联事件",并且只是在OnSpeak事件触发时运行特定代码的另一种方式。

x.OnSpeak += (s, e) => Console.WriteLine("On Speak!");

ssendere是事件参数。

您可以像这样重写代码,这可能更熟悉:

x.OnSpeak += OnSpeakEvent;

private static void OnSpeakEvent(object s, CancelEventArgs e)
{
    Console.WriteLine("On Speak!");
}