This article describes the CSharpThinking extension method. Share it for your reference. The specific analysis is as follows:
1. Evolution
① Characteristics of the extension method
1) Must be in a static method.
2) There is at least one parameter.
3) The first parameter must be prefixed with this keyword.
4) The first parameter cannot have any other modifiers (such as out, ref).
5) The type of the first parameter cannot be a pointer.
6) If the extension method name is the same as the type method (for example, both named ToString), only the type method will be called, and the extension method will not, which is a priority issue.
② Comparison of extension method and ordinary static method
When C#2 is used to extend 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 with classes.
{
// C#2 Normal calling method
string Log2 = ("C#2 ordinary static mode");
(Log2);
// C#3 extension method call method
string Log3 = "C#3 extension method".ToLogError();
(Log3);
();
}
/// <summary>
/// C#2 General static method extension
/// </summary>
/// <param name="loginfo">Format information</param>
/// <returns></returns>
public static string GetLogError(string loginfo)
{
return ("This is C#2 style: {0}", loginfo);
}
/// <summary>
/// C#3 string type extension implemented using extension method
/// </summary>
/// <param name="loginfo"></param>
/// <returns></returns>
public static string ToLogError(this string loginfo)
{
return ("This is C#3 style: {0}", loginfo);
}
2. The biggest purpose of the extension method is to use it in Linq.
① Where , Select , OrderBy,
Note: Sort will not change the order and type of the original sequence, and return a new sequence, which is different from that, which will change the sequence. So Linq has no side effects, except for some special circumstances.
(dept => new
{
Name = ,
Cost = (person=>);
})
.OrderByDescending(x=>);
② The extension method focuses more on results rather than process understanding, which is the difference from static methods.
I hope this article will be helpful to everyone's programming.