• 我知道这是事件参数的“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));
       }
     }
    }
    
  • 最佳答案

    这通常被称为“内联事件”,只是在 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!");
    }
    

    关于c# - "x.OnSpeak += (s, e)"是什么意思?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27667918/

    10-13 01:59