Anonymous Method
When your delegate is used one time, there is no real need for a separate, named method. Anonymous methods allow you to
dispense with the separate, named method.
An anonymous method is a method that is declared inline, at the point of instantiating a delegate.
You can use an anonymous method in the following places:
The code in the figure produces the following output:
An anonymous method is a method that is declared inline, at the point of instantiating a delegate.
delegate void operation(int x,int y); static class mathOperator { public static void add(int x,int y) { Console.WriteLine(x + " + " + y + " = " + (x + y)); } } class Program { static void Main(string[] args) { int x = 5; int y = 7; operation myOperator ; myOperator= mathOperator.add; myOperator(x, y); } } |
class Program { static void Main(string[] args) { int x = 5; int y = 7; operation myOperator = delegate(int param1,int param2) { Console.WriteLine(param1 + " + " + param2 + " = " + (param1 + param2)); }; myOperator(x, y); } } |
- As an initializer expression when declaring a delegate variable.
- On the right side of an assignment statement when combining delegates.
- On the right side of an assignment statement adding a delegate to an event.
Scope of Variables and Parameters
The scopes of parameters and local variables declared inside an anonymous method are limited to the body of the implementation code.Outer Variables
Unlike the named methods of a delegate, anonymous methods have access to the local variables and environment of the scope surrounding them.- Variables from the surrounding scope are called outer variables.
- An outer variable used in the implementation code of an anonymous method is said to be captured by the method.
Extension of a Captured Variable’s Lifetime
A captured outer variable remains alive as long as its capturing method is part of the delegate, even if the variable would have normally gone out of scope. For example:class Program { static void Main(string[] args) { operation myOperator=null; { int x = 5; int y = 7; myOperator = delegate(int param1,int param2) { Console.WriteLine(param1 + " + " + param2 + " = " + (param1 + param2)); Console.WriteLine("x = " + x + ", y = " + y); }; } myOperator(3,2); //in this line, x and y has been terminated } }
The code in the figure produces the following output:
3 + 2 = 5
x = 5, y = 7
x = 5, y = 7
0 comments:
Post a Comment