asp. CSharpThinking extension method analysis in net

  • 2021-01-22 04:59:13
  • OfStack

This article illustrates the CSharpThinking extension method in asp.net. Share with you for your reference. The specific analysis is as follows:

1. The evolution of

① Extended method features

1) Must be in a static method.
2) Have at least 1 parameter.
3) The first parameter must be prefixed with the this keyword.
4) The first parameter cannot have any other modifiers (e.g., out, ref).
5) The first parameter cannot be of type pointer.
6) If the extension method name is the same as the method name of the type (for example, both are named ToString), then only the method of the type will be called, but the extension method will not. This is a priority issue.

② Comparison between the extended method and the ordinary static method

In C#2, when extending a class without applying inheritance, you can only write slightly "ugly" static methods. C#3 allows us to change static classes to pretend that methods are innate to the class.

public static void Demo1()
{
     // C#2 Ordinary call mode
     string Log2 = ExtensionCompare.GetLogError("C#2 Normal static mode ");
     Console.WriteLine(Log2);      // C#3 Extend the way method calls are made
     string Log3 = "C#3 Extension method ".ToLogError();
     Console.WriteLine(Log3);      Console.ReadLine();
}
/// <summary>
/// C#2 Regular static method extensions
/// </summary>
/// <param name="loginfo"> Formatted message </param>
/// <returns></returns>
public static string GetLogError(string loginfo)
{
     return string.Format("This is C#2 style: {0}", loginfo);
}
/// <summary>
/// C#3 Implemented by extension methods string Type expansion
/// </summary>
/// <param name="loginfo"></param>
/// <returns></returns>
public static string ToLogError(this string loginfo)
{
     return string.Format("This is C#3 style: {0}", loginfo);
}

2. The biggest use of the extension method is in Linq.

① Where, Select, OrderBy,

Note: Sorting does not change the order or type of the original sequence and returns a new sequence. This is different from List.Sort, which changes the sequence. So Linq has no side effects, except in some very special cases.

company.Department.Select
(dept => new
{
     Name = dept.name,
     Cost = dept.Employees.Sum(person=>person.Salary);
})
.OrderByDescending(x=>x.Cost);

② The extended method pays more attention to the result rather than the process understanding, which is different from the static method.

Hope this article described to everybody asp.net program design is helpful.


Related articles: