What does "x.OnSpeak + = (s, e)" mean?
- I know "e" is for args event, but what does "s" mean here and "+ = (,) =>"?
-
Are there any other alternatives?
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)); } } }
+3
source to share
1 answer
This is often referred to as an "inline event" and is just another way to run certain code when an event occurs OnSpeak
.
x.OnSpeak += (s, e) => Console.WriteLine("On Speak!");
s
is sender
, and e
are the arguments of the event.
You can rewrite your code like this, which might be more familiar:
x.OnSpeak += OnSpeakEvent;
private static void OnSpeakEvent(object s, CancelEventArgs e)
{
Console.WriteLine("On Speak!");
}
+2
source to share