Recommendation 37: Use a lambda expression instead of a method and an anonymous method
In recommendation 36, we created such an instance program:
Static voidMain (string[] args) {Func<int,int,int> add =Add; Action<string> Print =Print; Print (Add (1,2). ToString ()); } Static intADD (intIintj) {returni +J; } Static voidPrint (stringmsg) {Console.WriteLine (msg); }
In fact, there are many different ways to do the same function. First of all, look at one of the most popular, but also the most tedious wording:
Static voidMain (string[] args) {Func<int,int,int> add =NewFunc<int, int, int>(ADD); Action<string> Print =NewAction<string>(Print); Print (Add (1,2). ToString ()); } Static intADD (intIintj) {returni +J; } Static voidPrint (stringmsg) {Console.WriteLine (msg); }
Note: The syntax above is tedious, but we can deepen our understanding of the nature of the delegate: The delegate is also a data type, no different from the reference type in any FCL.
You can also use anonymous methods:
func<int,int,int> add=Newfunc<int,int,int> (Delegate(intIintj) {returni +J; }); Action<string> print=Newaction<string> (Delegate(stringmsg) {Console.WriteLine (msg); });
Print (Add (1, 2). ToString ());
With anonymous methods, we don't need to declare two methods outside of the main method, so that all code can be written directly in the work method of main, without affecting the clarity of the code. In fact, all of the lines of code that are not more than 3 lines (provided that it is not reused) are recommended to be written in this way.
The improved version above is:
func<int,int,int> add=delegate(intint j) { return i + j; }; Action<string> Print=delegate(string msg) { Console.WriteLine (msg); };
Print (Add (1, 2). ToString ());
The final improvement version is using a lambda expression:
func<int,int,int> add= (i, j) = i + j; Action<string> Print= msg = Console.WriteLine (msg); Print (Add (12). ToString ());
The left side of the lambda expression operator "= =" is the method's parameter, and the right side is the method body, which is essentially an anonymous method. In fact, a compiled lambda expression is an anonymous method. We should skillfully use it in the actual coding to avoid cumbersome and unsightly code.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--recommendation 37: Using lambda expressions instead of methods and anonymous methods