This article illustrates the csharpthinking extension method in asp.net. Share to everyone for your reference. The specific analysis is as follows:
I. Evolution
① extension Method Features
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.
A comparison between ② extension method and ordinary static method
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.
Copy Code code as follows:
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.
①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.
Copy Code code as follows:
Company. Department.select
(Dept => New
{
Name = Dept.name,
Cost = Dept. Employees.sum (Person=>person. Salary);
})
. OrderByDescending (X=>x.cost);
② extension methods focus more on results than process understanding, which is different from static methods.
I hope this article will help you with the ASP.net program design.