Extension methods (Extension Method)

Source: Internet
Author: User
Tags export class
In oopl, there are static methods, instance methods, and virtual methods, as follows: public sealed class string {public static bool isnullorempty (string s ){//...} public String Replace (string old, string new ){//...}} public abstract class stream {Public Virtual void writebyte (byte value ){//...}} isnullorempty is a static method, replace is an instance method, and writebyte is a virtual method. Its usage is as follows: string name = NULL; console. writeline (string. isnullorempty (name); // true string S = "Hello, world! "; Console. writeline (S. Replace (" world "," C # "); // hello, C #! The virtual method must be redefined in the derived class. In C #3.0, another method is introduced, called extension method ): extension methods allow an exsting type to be extended with new methods without altering the definition of the original type. the extension method is to use a new method to extend the original type without modifying the definition of the original type. Extended original type (extending the existing type) The extended original type mechanism (means) has class inheritance, and the extension method in C. By adding new members to the class inheritance, you can extend the data members of the original type (fields ); you can define a new method or override a virtual method of the inherited class to extend the existing method member (methods ). However, the Inheritance Mechanism also has its own problems. If the original type declaration is a closed type (sealed class), the inheritance mechanism cannot be used to extend the original type (such as the above string class ). Furthermore, the extension of the export class to the base class is applied to the export class, not to the extension of the base class itself. Extension methods make up for the lack of inheritance mechanisms. Strictly speaking, the extension method is not a mechanism of the language itself, but a facility for using the syntax implemented by compiling programs. Whether the original type is closed or open, you can use the extension method for expansion. The extension method only extends the method members of the original class and does not extend the data members of the original class. An extension method is a static method of a static class, where the this modifier is applied to the first parameter. the type of the first parameter will be the type that is extended. the extension method is a static method of the static class. The first parameter must be modified with this, and the type of the first parameter is the type to be extended. Example: public static class stringhelper {public static bool iscapitalized (this string s) {If (string. isnullorempty (s) return false; return char. isupper (s [0]) ;}} iscapitalized is a static method defined on the static class, and its first parameter string S is modified with this, so iscapitalized is an extension method, because the type of the first parameter is string, iscapitalized expands to the string type. Usage: console. writeline ("Perth ". iscapitalized (); "Perth ". iscapitalized () is called directly for string "Perth" iscapitalized (), because iscapitalized () is a string extension method, so this call is acceptable. After the extension method is parsed by the compiler, it is translated as a normal static method call, that is, console. writeline (stringhelper. iscapitalized ("Perth"); and "Perth ". iscapitalized () is relative to stringhelper. iscapitalized ("Perth") is more natural and concise. Therefore, the extension method is still a static method, but the syntax introduced by the C # language is used. The compiler translation process is as follows: arg0.method (arg1, arg2 ,...); ==> staticclass. method (arg0, arg1, arg2 ,...); that is, the call of the extension method is translated into a normal static call. Although the string class of the application of the extension method provides many powerful methods, it is always impossible to meet all requirements. Some features that are frequently used but not provided by the string class can be written as extension methods and incorporated into the library, which can be used in multiple projects. The following is an example of two string-related extension methods in the stringextensions class: public static class stringextensions
{
Public static list <keyvaluepair <string, string> listize (this string SS)
{
List <keyvaluepair <string, string> plist = new list <keyvaluepair <string, string> ();
String [] slist = ss. Split (New char [] {';'});
Foreach (string s in slist)
{
If (string. isnullorempty (s) continue;
String [] pair = S. Split (New char [] {':'});
If (pair. length! = 2) continue;
Plist. Add (New keyvaluepair <string, string> (pair [0], pair [1]);
}
Return plist;
}
Public static string matchandreplace (this string SRC, string pattern, string DST)
{
List <string> MList = new list <string> ();
Foreach (Match m in RegEx. Matches (SRC, pattern ))
{
MList. Add (M. value );
}
Foreach (string s in MList)
{
If (string. isnullorempty (s) continue;
Src = SRC. Replace (S, DST );
}
Return SRC;
}
} Use Cases of the preceding two extension methods: String SQL = getsql (); string wheretail = "";
Foreach (string K in Po. customobject. Keys)
{
If (string. isnullorempty (k) continue;
If (string. Compare (k, "demo-onelist", true) = 0)
{
Wheretail = Po. customobject [K]. value. listize (). buildwhereclauserandom sive ();
}
Else if (string. Compare (k, "nondemo-onelist", true) = 0)
{
Wheretail = Po. customobject [K]. value. listize (). buildwhereclauseexclusive ();
}
}
If (! String. isnullorempty (wheretail ))
{
SQL = SQL. matchandreplace ("1 [] * = [] * 1", wheretail );
} We can see that the string extension method is called like a native method (a method defined by the string class), and the Code looks more natural and concise. The Extension Method mechanism is introduced to solve the problem of LINQ. For this reason, we should also describe it in another article. For more information about the extension method, see C # In depth third edition.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.