Prev | Current Page 127 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

NET Framework are best used. Over time, this will lead to a different way of
approaching code.
C# 1 has pretty clumsy syntax when it comes to creating a delegate instance. For one
thing, even if you need to accomplish something very straightforward, you??™ve got to have
a whole method dedicated to that job in order to create a delegate instance for it. C# 2
55 C# 2 and 3: new features on a solid base
fixes this with anonymous methods, and introduces a simpler syntax for the cases where
you still want to use a normal method to provide the action for the delegate. You can also
create delegate instances using methods with compatible signatures??”the method signature
no longer has to be exactly the same as the delegate??™s declaration.
Listing 2.4 demonstrates all these improvements.
static void HandleDemoEvent(object sender, EventArgs e)
{
Console.WriteLine ("Handled by HandleDemoEvent");
}
...
EventHandler handler;
handler = new EventHandler(HandleDemoEvent);
handler(null, EventArgs.Empty);
handler = HandleDemoEvent;
handler(null, EventArgs.Empty);
handler = delegate(object sender, EventArgs e)
{ Console.WriteLine ("Handled anonymously"); };
handler(null, EventArgs.Empty);
handler = delegate
{ Console.WriteLine ("Handled anonymously again"); };
handler(null, EventArgs.Empty);
MouseEventHandler mouseHandler = HandleDemoEvent;
mouseHandler(null, new MouseEventArgs(MouseButtons.


Pages:
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139