1. Before
c# 2.0, delegate could be declare
only using named methods.
2. C#
introduced anonymous methods and same can be
used for delegate.
// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
{
System.Windows.Forms.MessageBox.Show("Click!"); };
or
// Create a delegate instance
delegate void Del(int x);
// Instantiate the delegate using an anonymous method
Del d = delegate(int k) { /* ... */ };
4. Another good example would be when launching a new thread. This class creates a thread and also contains the code that the thread executes, without the need for creating an additional method for the delegate.
void StartThread()
{
System.Threading.Thread
t1 = new System.Threading.Thread
(delegate()
{
System.Console.Write("Hello, ");
System.Console.WriteLine("World!");
});
t1.Start();
}
5. The scope of the parameters of an
anonymous method is anonymous-method-block.6. It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. Similarly it is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.
7. The local variables and parameters whose scope contain an anonymous method declaration are called outer or captured variables of the anonymous method. For example, in the following code segment,
n is an outer
variable:
int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy
#:{0}", ++n); };
n is captured at the time the delegate is
created.9. An anonymous method cannot access the ref or out parameters of an outer scope.
10. Two ways of instantiating a delegate:
·
Associating the delegate with an anonymous method.
·
Associating the delegate with a named method (
In each case, a message is displayed when
the delegate is invoked.DoWork).
// Declare a delegate
delegate void Printer(string s);
class TestClass
{
static void Main()
{
//
Instatiate the delegate type using an anonymous method:
Printer p = delegate(string j)
{
System.Console.WriteLine(j);
};
// Results
from the anonymous delegate call:
p("The
delegate using the anonymous method is called.");
// The
delegate instantiation using a named method "DoWork":
p = new Printer(TestClass.DoWork);
// Results
from the old style delegate call:
p("The
delegate using the named method is called.");
}
// The
method associated with the named delegate:
static void DoWork(string k)
{
System.Console.WriteLine(k);
}
}
Output
The delegate using the anonymous method is called.
The delegate using the named method is called.
No comments:
Post a Comment