Extension methods from simple application to in-depth analysis, reading this article is enough

Source: Internet
Author: User

Preface (RIP-_-)

Hello everyone, today and you talk about the expansion of the matter, I will take everyone from the simple application began to understand the principle of extension methods, and the use of extension methods to give reasonable suggestions.

In practical applications, when we use a class to find that the class is missing the method we want, the simplest and most straightforward is to modify the source code of the class to add the method we want. But the fact is often unsatisfactory, always because of a variety of factors can not directly modify the source code: Do not get the source code, not allowed to modify, this time through the inheritance and extension of the way to re-use is better, but if the last inheritance of the rights are deprived of the words (sealed class is not allowed to inherit)? ... This is the time to use the "extension method".

Introduction to extension methods

Let's take a look at the theory first (everyone, don't worry, just wait for the code):
The extension method is a new feature introduced in c#3.0 that allows you to add new methods to a class without having to use inheritance to create a new class, or to modify the original class. You can invoke the new method directly using an instance of the original type object.

It must meet the following requirements (important):

    1. Must be a static method defined in a static class;
    2. The type of the first parameter is the type to be extended;
    3. The first parameter needs to add the This keyword to identify it as an extension method.


Simple Application

We use the string type to give an example: There are many methods in the string class, such as the usual A. ToString ();

Now we want to add a method to the string class to get how many words are contained in a string

Let's look at both of these approaches:

a direct new method (generic, but not a new method for the string class, written here for comparison)

 Public classTool {

Public Static intGetwordcount (stringStr
{
returnStr. Split (New Char[]{' ',',','?'},stringsplitoptions.removeemptyentries). Length;
}
}
Call:
strings="myTest string. Yeyeye";
intCount=tool.getwordcount (s);

A Getwordcount method is built directly in tool tools, and a direct value call is


Ii. the way of inheritance ( Note: The string class is not allowed to be inherited here for comparison )

 Public classmystring:string {
Public intGetwordcount ()
{
return This. Split (New Char[]{' ',',','?'},stringsplitoptions.removeemptyentries). Length;
}
}
Call:
MyString s="myTest string. Yeyeye";
intCount=s.getwordcount ();

Iii. ways to extend methods
In addition to the above two methods, what is the way? Now let's take a look at not using inheritance to add a method to the string class?

 Public Static classMyextension {
Public Static intGetwordcount ( This stringStr
{
returnStr. Split (New Char[]{' ',',','?'},stringsplitoptions.removeemptyentries). Length;
}
}

Call:

strings="myTest string. Yeyeye";
intCount=s.getwordcount ();

As above; This is an extension method, note the 3 positions of the red flag, and static methods in the static class identify the type with the This keyword.


Let's compare them.

    1. The first is a more generic approach and is usually the most used, but the readability of the code is not as good as the extension method compared to the extension method.
    2. The way to inherit is a good extension, but sometimes it is not necessarily perfect, for example: a. Each inheritance produces a new class, and a corresponding cast (string=>mystring) is required for use, B. Some classes themselves are designed as sealed classes and are not allowed to be inherited. The example string used above is not allowed to be inherited, so the second scenario is not feasible. at this point, the third method of solution expansion comes in handy.


Let's take a look at the use of extension methods:

 Public Static classmyextension{
Public Static intGetwordcount ( This stringStr
{
returnStr. Split (New Char[]{' ',',','?'},stringsplitoptions.removeemptyentries). Length;
}
}
Call:

strings="myTest string. Yeyeye";
intCount=s.getwordcount ();

Note: We can use the new extended method only after referencing the namespace of myextension.

See this, I believe that we have been able to skillfully use the extension method, now we have to dig into the principle of extension methods.

Deep understanding of extension methods

The following is an excerpt from the analysis and collation of CSDN-SIMONEZHLX: The extension method Stringtoupper, using the S instance to directly use the new extended method

Let's take a look at the IL code that comes back with reflector:

As you can see, the extension method call in Il has been interpreted as a simple static method call. What does that mean?

The extension method is nothing more than a simple way to invoke a static method , making the code more natural to write. In other words, the final compiler is still a static method call that transforms an extension method into a static class
Now that the compiler has converted to a static method call, how does the compiler tell you that this is an extension method ? Keep looking at the following:

We can see that the extension method we write is interpreted as a static method in the compilation that contains the specified attribute (ExtensionAttribute), which makes the compiler understand that the method is actually an extension method

How do we tell if it is an extension method?

The extension method is distinguished by the following:

1. Blue Arrow

2. Include (extension) the prompt information

Extension methods that you might have used:

If you've ever used LINQ, you'll find that the relationship between LINQ and extension methods is so close!

So many blue arrows, hehe ....

Some summary of extension methods

    1. You can add a new method to a class without having to use inheritance to create a new class, or to modify the original class;
    2. If the extension method has the same signature as a method in the class, the extension method is not called, that is, the extension method is overwritten by the method with the same name as the extended class, so implementing the extension method requires that we assume the risk of being overwritten at any time (for example, if you extend the ToString () in a String class, The extension method is not valid at this time);
    3. Extension methods cannot access private members of the extended class
    4. An extension method can only be invoked using an instance, and cannot be called with a class name like a normal static method;
    5. Extension methods can only be used if the namespace in which the extension method resides is introduced.

Use selection for Extended method attributes
"Generally, it is recommended that you implement extension methods only when you have to, and implement them with caution," the Microsoft company documentation says. Whenever possible, client code that must extend an existing type should achieve this by creating a new type derived from an existing type. "
However, through some examples of our analysis, the extension method should be the preferred scheme in some specific situations. If your library itself is functional enough to meet most applications, just a series of extensions for a particular domain, industry, or special application, we can use the extension method to organize these functions and get a dedicated extension method library to add optional new features to the library without changing the library code.

This is like a laptop USB, do not need to integrate all the function points on the computer, we just need to memory, hard disk and other needs of the functions of the integration can be, through the USB extension of other new functional devices, through the extension of the method to meet the needs of individual users of the function point.


About the extension type to share this, everyone in the use of flexible use can be. Related resource acquisition or other questions can be codel in the public number.

Extension methods from simple application to in-depth analysis, reading this article is enough

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.