This chapter mainly describes the application of extension methods and related principles.
One, evolution
1.1 Extension Method characteristics
1 must be in a static method.
2) at least one parameter.
3 The first argument must be appended with the This keyword as a prefix.
4 The first parameter cannot have any other modifiers (such as Out,ref).
5 The type of the first argument cannot be a pointer.
6 If the extension method name is the same as the method of the type (for example, all named ToString), only the type of method is invoked, and the extension method is not, which is a priority issue.
Comparison of 1.2 extension methods with ordinary static methods
When c#2 an extension to a class without applying an inheritance method, you can only write a slightly "ugly" static method. C#3 allows us to change the static class to pretend that the method is inherent in the class.
The code is as follows |
Copy Code |
public static void Demo1 () { C#2 Normal Calling Mode String Log2 = Extensioncompare.getlogerror ("c#2 normal static Mode"); Console.WriteLine (LOG2);
How C#3 extension method calls String Log3 = "c#3 extension method." Tologerror (); Console.WriteLine (LOG3);
Console.ReadLine (); }
<summary> C#2 General static Method extension </summary> <param name= "Loginfo" > Formatting information </param> <returns></returns> public static string Getlogerror (String loginfo) { return string. Format ("This is c#2 style: {0}", Loginfo); } <summary> C#3 string extension implemented with extension methods </summary> <param name= "Loginfo" ></param> <returns></returns> public static string Tologerror (this string loginfo) { return string. Format ("This is c#3 style: {0}", Loginfo); } |
Second, the most important use of extension methods is in LINQ.
2.1. Where, Select, by
Note: Sorting does not change the order and type of the original sequence, it returns a new sequence, unlike List.sort, which changes the sequence. So LINQ has no side effects, except for some of its special circumstances.
The code is as follows |
Copy Code |
Company. Department.select (Dept => New { Name = Dept.name, Cost = Dept. Employees.sum (Person=>person. Salary); }) . OrderByDescending (X=>x.cost);
|
2.2. Extension methods focus on results rather than process understanding, which is different from static methods.