.net 3.5 introduced Linq and lambda expressions, so the creation of delegates has become simpler and more elegant.
After the introduction of lambda expressions, there is no need to use anonymous methods, making the way to create delegates simpler and more elegant. In fact, if the lambda expression is introduced first, there will be no anonymous method.
Lambda expressions are written in C# as "arg-list => expr-body". The left side of the "=>" symbol is the parameter list of the expression, and the right side is the expression body. (body). The parameter list can contain 0 to more parameters, separated by commas.
1 namespace DelegateDemo 2 { 3 //声明委托 4 public delegate void MyDel(string arg1, string arg2); 5 6 class Program 7 { 8 static void Main(string[] args) 9 {10 //.net 3.5中的委托11 12 //创建委托,使用lambda表达式代替匿名方法13 MyDel myDel = (string arg1, string arg2) =>14 {15 Console.WriteLine(string.Format("arg1:{0},arg2:{1}", arg1, arg2));16 };17 18 //调用委托19 myDel("aaa", "bbb");20 21 Console.ReadKey();22 }23 }24 }
Because the compiler can know the type of the delegate parameter from the delegate declaration (this feature is called type deduction), so Allows us to omit parameter types, so the code simplifies to the following.
1 //创建委托,使用lambda表达式代替匿名方法2 MyDel myDel = (arg1, arg2) =>3 {4 Console.WriteLine(string.Format("arg1:{0},arg2:{1}", arg1, arg2));5 };
Note, if there is only one parameter, you can also omit the parentheses around the parameter type.
Because lambda expressions allow the expression body to be a statement or statement block, so when the expression body has only one statement, you can replace the statement block with a statement to continue simplification. . The following code:
1 //创建委托,使用lambda表达式代替匿名方法2 MyDel myDel = (arg1, arg2) => Console.WriteLine(string.Format("arg1:{0},arg2:{1}", arg1, arg2));
The above is the detailed content of About delegate instances in .net 3.5. For more information, please follow other related articles on the PHP Chinese website!