Anonymous Method
- An anonymous method is a method without a name - which is
why it is called anonymous. You
don't declare anonymous methods like regular methods.
Instead they get hooked up directly to
events. You'll see a code example shortly.
- To see the benefit
of anonymous methods, you need to look at how they improve your
development experience over using delegates. Think about all
of the moving pieces there are with
using delegates: you declare the delegate, write a method
with a signature defined by the delegate
interface, delcare the event based on that delegate, and
then write code to hook the handler method
up to the delegate. With all this work to do, no wonder
programmers, who are new to C#
delegates, have to do a double-take to understand how they
work. Because you can hook an
anonymous method up to an event directly, a couple of the
steps of working with delegates can be
removed.
- The code in Listing
below is a Windows Forms application. It instantiates a Button control and
sets its Text to "Hello". Notice the combine,
+=, syntax being used to hook up the anonymous
method. You can tell that it is an anonymous method because it uses the delegate keyword,
followed by the method body in curly braces. Remember to
terminate anonymous methods with a
semi-colon.
Implementing an Anonymous Method:
-Open windows form application
public Form1()
{
InitializeComponent();
Button
btnHello = new Button();
btnHello.Text = "Hello";
btnHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Controls.Add(btnHello);
}
No comments:
Post a Comment