Home > Backend Development > C#.Net Tutorial > About delegate instances in .net 3.5

About delegate instances in .net 3.5

零下一度
Release: 2017-06-23 16:05:19
Original
1514 people have browsed it

 .net 3.5 introduced Linq and lambda expressions, so the creation of delegates has become simpler and more elegant.

.net 3.5 Delegates

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 }
Copy after login

Omit parameter type

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 };
Copy after login

Note, if there is only one parameter, you can also omit the parentheses around the parameter type.

Use statements to replace expressions

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));
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template