Previous: http://www.bkjia.com/kf/201208/150595.html
In C # versions earlier than 2.0, the only way to declare a delegate is to use the naming method. C #2.0 introduces anonymous methods. In C #3.0 and later versions, Lambda expressions replace anonymous methods as the preferred method for writing Inline code. However, the information about anonymous methods in this topic also applies to Lambda expressions. In one case, the anonymous method provides functions not available in Lambda expressions. You can use the anonymous method to ignore the parameter list. This means that the anonymous method can be converted to a delegate with various signatures. This is not possible for Lambda expressions.
The anonymous method provides the ability to declare the delegate object using code blocks. If the anonymous method is used, you do not need to create an independent method. Therefore, the coding system overhead required to instantiate the delegate is reduced.
[Csharp]
Void StartThread ()
{
System. Threading. Thread t1 = new System. Threading. Thread
(Delegate ()
{
System. Console. Write ("Hello ,");
System. Console. WriteLine ("World! ");
});
T1.Start ();
}
1. Ignore proxy Parameters
If the proxy implementation does not depend on its parameters, you can remove the entire parameter list and only use the delegate keyword and statement block.
[Csharp]
Button. MouseClick + = delegate {Console. WriteLine ("LogMouse ");};
Ii. Capture external variables
If a local variable and a parameter have an anonymous method declaration, the local variable and parameter are called an external variable. If an external variable is used by an anonymous method, the external variable is called capture external variable or capture variable for short. For example, n in the following code segment is a capture variable:
[Csharp]
Int n = 0;
Del d = delegate () {System. Console. WriteLine ("Copy #:{ 0}", ++ n );};
Unlike local variables, the life cycle of the capture variable continues until any proxy object that references the capture variable meets the garbage collection condition. This is the key to capturing external variables. For example:
[Csharp]
List <MethodInvoker> list = new List <MethodInvoker> ();
For (int index = 0; index <5; index ++)
{
Int counter = index * 10;
List. Add (delegate
{
Console. WriteLine (counter );
Counter ++;
});
}
Foreach (MethodInvoker t in list)
{
T ();
}
List [0] ();
List [0] ();
List [0] ();
List [1] ();
Output:
0
10
20
30
40
1
2
3
11
[Csharp] view plaincopy
List <MethodInvoker> list = new List <MethodInvoker> ();
For (int index = 0; index <5; index ++)
{
List. Add (delegate
{
Console. WriteLine (index );
Index ++;
});
}
Foreach (MethodInvoker t in list)
{
T ();
}
List [0] ();
List [0] ();
List [0] ();
List [1] ();
Output:
5
6
7
8
9
10
11
12
13