2014-12-27 79 views
3
  • 我知道這是事件參數的「e」,但這裏的「s」是什麼意思,「+ =(,)=>」是什麼意思?
  • 是否有其他替代實現?「x.OnSpeak + =(s,e)」是什麼意思?

    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

它不再是含糊不清,我就接受了幾分鐘後,回答 – Kinani 2014-12-27 14:10:16

+1

這是一個['匿名Method'] (http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx)聲明。 – Avijit 2014-12-27 14:10:31

+2

'(s,e)=> Console.WriteLine(「在說話!」)是一個lambda。您可能需要閱讀C#中的lambda表達式。 – 2014-12-27 14:10:43

回答

2

這通常被稱爲「內聯事件」,並且是在運行特定的代碼OnSpeak事件觸發時的另一種方式。

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

ssender,和e是事件參數。

你可以重寫你這樣的代碼,這可能是更熟悉的前瞻性:

x.OnSpeak += OnSpeakEvent; 

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