Recommendation 150: Use an anonymous method, a lambda expression instead of a method
If the method body is too small (such as less than 3 lines), it is too cumbersome to define a method specifically for this purpose. Like what:
Static voidSampemethod () {List<string> list=Newlist<string> () {"Mike","Rose","Steve"}; varMike = list. Find (Newpredicate<string>(havelengthfive)); Console.WriteLine (Mike); } Static BOOLHavelengthfive (stringvalue) { returnValue. Length = =5; }
In the above code, the SampleMethod method needs to be done to see if there are no elements of length equal to 5 in the list. predicate is a delegate that receives the value of an element and returns the result of whether the element meets the requirements. And the code that really works is only 1 lines. Some tedious, so to refactor:
Static voidSampemethod () {List<string> list=Newlist<string> () {"Mike","Rose","Steve"}; varMike = list. Find (Delegate(stringValue) {returnValue. Length = =5; }); Console.WriteLine (Mike); }
The statement led by delegate is an anonymous method. Secondly, after the compiler compiles the anonymous method, it is no different from the normal method. The anonymous approach brings only part of the work of simplifying the programmer.
A better method of simplification is a lambda expression. The lambda expression is signed with the "= =" Connection (read as "goes to"), the left side of the symbol is the argument list, and the right is the method body. Lambda expressions further simplify the syntax of anonymous methods:
Static void Sampemethod () { List<string> list=new list<string> () {"Mike ","Rose","Steve"}; var 5 ); Console.WriteLine (Mike);
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
"Go" writing high-quality Code 157 recommendations for improving C # Programs--Recommendation 150: Using anonymous methods, lambda expressions instead of methods