. NET 3.5 introduces Linq,lambda expressions, so the creation of delegates is simpler and more elegant.
Delegates in. NET 3.5
With the introduction of lambda expressions, you don't need to use anonymous methods anymore, making it easier and more elegant to create delegates. in fact, if lambda expressions were introduced first, there would be no anonymous method.
The lambda expression is written in C # as "arg-list = Expr-body", the "= =" symbol to the left of the argument list of the expression, and the expression body (body) on the right. The argument list can contain between 0 and more parameters, separated by commas.
1 namespace Delegatedemo 2 {3 //Declaration Delegate 4 Public delegate void Mydel (string arg1, String arg2); 5 6 class Pr Ogram 7 {8 static void Main (string[] args) 9 {Ten //.net 3.5 delegates each //create delegates, use lambda expressions instead of anonymous methods 13< C10/>mydel Mydel = (string arg1, String arg2) =>14 { Console.WriteLine (string. Format ("Arg1:{0},arg2:{1}", Arg1, Arg2)), };17 (" aaa", "BBB" ); Console.readkey (); }23 }24}
Omitting parameter types
Because the compiler can know the type of the delegate parameter from the delegate declaration (this attribute is called type deduction), it allows us to omit the parameter type, so the code is simplified to the following.
1//Create delegate, use lambda expression instead of anonymous Method 2 Mydel Mydel = (arg1, arg2) =>3 {4 Console.WriteLine (string. Format ("Arg1:{0},arg2:{1}", Arg1, Arg2)); 5};
Note that if there is only one parameter, you can omit the parentheses around the parameter type.
Replacing an expression with a statement
Because lambda expressions allow an expression body to be a statement or statement block, you can continue simplifying a statement instead of a statement block when the expression body has only one statement. The following code:
1//Create delegate, use lambda expression instead of anonymous Method 2 Mydel Mydel = (arg1, arg2) = Console.WriteLine (String. Format ("Arg1:{0},arg2:{1}", Arg1, arg2));