C # Literacy: Take you through the expansion methods of C # and explore the nature and considerations of extension methods

Source: Internet
Author: User

1. Why you need to extend the method

. NET3.5 gives us the concept of an extension method that allows you to add a new method to a class or struct without modifying the original structure of the type to be added.

Think: So why do we need to expand the method, why not directly modify the original type?

First, let's say we have a class in our project, and after a while, we know that we need to add a new feature to the class, and there are two workarounds for this requirement:

(1) Modify the definition of the current class directly

The disadvantage of this is that it destroys backwards compatibility and may not be compiled by old code that was previously used. For example, the old code used a methed (Int,int) method, but in order to meet the new functionality we now modify the methed (Int,int,int), adding a parameter, so that the old code can not be compiled.

(2) Deriving from the current class as a base class and implementing it in a subclass

This is also a disadvantage, that is, if the function needs to be modified, we need to maintain two places, one is the parent class, one is a subclass, increase the workload of code maintenance

At this point, the new feature extension method solves the above two problems, and also resolves the implementation of some classes are third-party, we can not modify the source code situation, and some classes are not inheritable, can not be derived, in both cases the extension method may be used to add new features. With extension methods, you can modify a type without creating a subclass and directly modifying the type.

2. How to use the extension method

2.1 Rules

The definition extension method must follow two Static and a this:

1. The extension method must be defined in a static class, and each extension method must also be declared as a static
2. All extension methods must be decorated with the first parameter using the This keyword

Implementation of the extension method as shown, we want to extend a function to the StringBuilder system type to extract the index of a character in a string object

2.1 Calling extension methods at the instance level

Calling an extension method at the instance level means calling on the instance of the extended object instead of using the static class call we defined. See the code for details on how to invoke it.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceexstensionmethd{classProgram {Static voidMain (string[] args) {StringBuilder Tmpstr=NewStringBuilder ("12323"); Console.WriteLine (Tmpstr.stringindef ('2'));//Here we are using an instance of StringBuilder tmpstr to call directlyConsole.readkey (); }    }    /// <summary>    ///extension method Static class/// </summary>    Static classExtionclass { Public Static intStringindef ( ThisStringBuilder STR,CharTmpchar) {            intindex =0;  for(; index < Str. Length; index++)            {                if(Str[index]. Equals (Tmpchar)) {returnindex; }            }            return-1; }    }}
instance hierarchy call extension method

Note: It is necessary to note that an extension method can have multiple parameters, but the position of the first parameter is always the extension object and cannot be changed. That is, only the first parameter can and must be decorated with the This keyword, and other parameters are treated as normal parameters of the method.

3, the definition of extension method location

When defining an extension method, that is, when defining an extension method static class, we must specify a namespace for it, and if the namespace is different from the namespace in which you want to use the extension method, you need to import the namespace (using the Use keyword). It is recommended that the extension method be defined as the same namespace as the type that will be extended. For example, the system type Stringbulder in our example above is System.Text, we can add a new class, and then define the namespace as System.Text, that is, preferably a global, outermost namespace, The benefits of doing so will be explained below.

4, the essence of the extension method

The essence of the extension method is actually implemented by the compiler to adopt the principle of mirroring, does not change the original type or add something extra, see the IL code after the translation, you can see the address we marked with a red box, call Int32 Exstensionmethd.extionclass::stringindef (class [Mscorlib]system.text.stringbuilder,char) Its essence still calls the original static class of the public static method only.


So tmpstr.stringindef (' 2 ') in the Code and extionclass.stringindef (Tmpstr, ' 2 ') are equivalent , Why, however, we can use the instance invocation directly, because the compiler does the work silently.

Compiler work---------------------------------------

  Tmpstr.stringindef (' 2 ')

When the compiler sees the following code, the compiler works in two steps:

(1) The compiler checks the current type of tmpstr, that is, the Stringbulder class and whether any base class Stringbulder has a matching function named Stringindef that contains a char parameter, if found , the IL code is generated and call it;

(2) If no matching method is found, proceed to check if any static class defines a static method named Stringindef, and the method must be decorated with the This keyword and the parameter type is Stringbulder. Generate the appropriate IL code to call it when found

So that's how we define the extension method, because the compiler just matches the rules to generate IL code for it, but even if we define the extension method, other programmers don't know, so it's not superfluous, it's not. As the Universe vs. a powerful compiler, it uses the "IntelliSense" function to simplify our use of extension methods, when we use extended type instances, when the point number is pressed, vs automatically add the extension method let us choose, for our programmer, It is like the original method of using the extension object directly. That's what the VS compiler did for us.

5. Extending various types using extension methods

The extension object of an extension method can be a class, an interface, a delegate type, and so on. When an interface is extended, all classes that implement this interface have this extension method.

classProgram {Static voidMain (string[] args) {            "123123123123". Showitems ();//string            New[] {1,2,3,4, }. Showitems ();//int array            Newlist<int> {1,2,3,4}. Showitems ();//List ContainerConsole.readkey (); }    }    /// <summary>    ///extension method Static class/// </summary>    Static classExtionclass { Public Static voidShowitems<t> ( ThisIenumerable<t>colletion) {            foreach(varIteminchcolletion) {                if(item is string) Console.WriteLine (item); ElseConsole.WriteLine (item.            ToString ()); }        }    }
extension methods for interfaces

6. Usage Considerations for extension methods

    • C # supports extension methods, does not support extended attributes, extended events, extended operators, etc.;
    • The extension class must be defined in a non-generic static class and cannot be a generic class, and the extension class name can be arbitrarily defined. "Why can't it be a generic static class, you know?" If you really do not know, the above content you did not look closely, because the extension method is actually compiled at compile time to match and compile, and the generic class only at run time to really determine its specific type, so it can not be a generic static class ";
    • The definition of an extension method must have a file scope, meaning it must be defined directly under a namespace in the file, and cannot be nested within another class;
    • Multiple static classes can define the same extension method, which requires attention to explicitly invoking the object at invocation time. When a conflict is invoked, the instance call can no longer be used. Only static classes can be used. The method is used in the ordinary way;
    • If the extension of this class is a base class, and it has a lot of derived classes, then its derived class also has this extension method (as above we extend the interface), there is a benefit and disadvantage, the advantage is that the subclass can use this method, the disadvantage is that the smart hint will have recursion, there are a lot of garbage information filled;
    • The extension method has a version problem. As we said earlier, the compilation will first look for whether the class defines a matching method before it goes back to finding the static class. So if we now define a indexof method, and in later versions of Microsoft, the official adds the same method named IndexOf, then our static method will not be called.
Reference: Proficient in C # (6th edition)
CLR via C # (4th edition)

Due to the knowledge of this talent, the description is inevitably flawed, if there are errors, welcome to point out. You!

C # Literacy: Take you through the extension methods of C #, and explore the nature and considerations of extension methods

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.