From simple application to in-depth analysis of the extension method, read this article.

Source: Internet
Author: User

From simple application to in-depth analysis of the extension method, read this article.

Preface (nonsense -_-)

Hello everyone, today I will talk about expansion. I will take you through a simple application to understand the principles of the extension method and give reasonable suggestions on the use of the extension method.

In practical applications, when we use a class, we find that the class lacks the method we want. The simplest and most direct method is to modify the class source code to add the method we want. However, the fact is often unsatisfactory, and the source code cannot be directly modified due to various factors: The Source Code cannot be obtained, and the modification is not allowed. At this time, it would be better to reuse it through inheritance and extension, but if the last inherited right is denied (the seal class does not allow inheritance )?... In this case, you need to use the [extension method.

Extended Methods

Let's take a look at the theory first (don't worry, you'll just go to the code later ):
The extension method is a new feature introduced in C #3.0. It can be used to add new methods to the class, without the need to use inheritance to create a new class or modify the original class. You can directly call the new method by using an instance of the original type object.

It must meet the following requirements (important ):

  1. It 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 useStringFor example, there are many methods in the string class, such as a. ToString ();

Now we wantAdd a method to the string classUsed to obtain the number of words contained in a string.,

Let's take a look at these two methods:

1. directly create a new method (common, but not adding a new method to the string class, which is written here for comparison) 

Public class Tool {

Public static int GetWordCount (string str)
{
Return str. Split (new char [] {'', '? '}, StringSplitOptions. RemoveEmptyEntries). Length;
}
}
Call:
String s = "myTest string. yeyeye ";
Int count = Tool. GetWordCount (s );

Create a GetWordCount method directly in the Tool class Tool and directly call the value.


Ii. Inheritance Method (Note: The String class cannot be inherited for comparison)

Public class MyString: String {
Public int GetWordCount ()
{
Return this. Split (new char [] {'', '? '}, StringSplitOptions. RemoveEmptyEntries). Length;
}
}
Call:
MyString s = "myTest string. yeyeye ";
Int count = s. GetWordCount ();

 

Iii. Method of Extension
In addition to the above two methods, what are the other methods? Next let's take a look at how to add a method to the string class without using inheritance?

Public static class MyExtension {
Public static int GetWordCount (this string str)
{
Return str. Split (new char [] {'', '? '}, StringSplitOptions. RemoveEmptyEntries). Length;
}
}

Call:

String s = "myTest string. yeyeye ";
Int count = s. GetWordCount ();

This is an extension method. Pay attention to the three positions marked in red. The static method in the static class uses the this keyword to identify the type.


Let's make a comparison;

  1. The first method is a common method, which is usually the most commonly used method. However, compared with the extension method, the Code is not as readable as the extension method.
  2. The inheritance method is a good extension scheme, but sometimes it is not necessarily perfect, for example:. each inheritance will produce a new class, and the corresponding forced conversion (string => MyString), B. some classes are designed as Sealed Classes and cannot be inherited. The strings used in the above example are not allowed to be inherited, so the second method is not feasible.In this case, the third method will be used.


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

Public static class MyExtension {
Public static int GetWordCount (this string str)
{
Return str. Split (new char [] {'', '? '}, StringSplitOptions. RemoveEmptyEntries). Length;
}
}
Call:

String s = "myTest string. yeyeye ";
Int count = s. GetWordCount ();,

Note: The new extension method can be used only when the namespace of MyExtension is referenced.

Seeing this, I believe everyone is familiar with the extension method. Now let's take a deeper look at the principle of the extension method.

 

In-depth understanding of extension methods

The following is an analysis taken from CSDN-simonezhlx and sorted out: the extension method StringToUpper. Using the s instance, you can directly use the new extension method.

Let's take a look at the IL code decompiled by Reflector:

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

The extension method is just a simple method to call static methods.To make the code write more natural. In other words,In the end, the compiler still converts the Extension Method to the static method call of the static class.
Since it is converted into a static method call method after compilationHow does the compiler identify that this is an extension method?? Continue to see the following:

We can see that the extension method we write is interpreted as a static method containing the specified ExtensionAttribute in compilation. This feature makes the compiler clear that this method is actually an extension method.

 

How can we identify whether it is an extension method?

The extension method is identified as follows:

1. Blue Arrow

2. prompts containing (extension)

You may have used the following extension methods:

If you have used Linq, you will find that the relationship between Linq and the extension method is so close!

So many blue arrows, huh, huh ....

 

Summary of extension methods

  1. You can add a new method to the class without using inheritance to create a new class or modifying the original class;
  2. If the extension method has the same signature as the method in the class, the extension method will not be called, that is, the extension method will be overwritten by the method with the same name as the extension class, therefore, to implement the extension method, we need to bear the risk of being overwritten at any time (for example, if ToString () in a string class is extended, the extension method is invalid at this time );
  3. The extension method cannot access the private members of the extended class.
  4. Extension methods can only be called by instances. They cannot be called by class names like normal static methods;
  5. The extension method can be used only after the namespace of the extension method is introduced.

Use of extended method features
As mentioned in Microsoft documents, "we recommend that you implement the extension method only when you have to, and exercise caution. If possible, client code of the existing type must be extended by creating a new type derived from the existing type. "
However, according to some of our instance analysis, the extension method should be the preferred solution in some specific scenarios. If your class library is fully functional and can meet the needs of a vast majority of applications, you can use the extension method to organize a series of function extensions for a certain field, industry, or special application, get a dedicated extended keystore library and add optional new functions for the library without changing the library code.

This is just like the USB of a laptop. We don't need to integrate all the function points into the computer. We only need to integrate all the functions required by the memory and hard disk, expand other new function devices by using USB and meet the requirements of individual users by using expansion methods.


Let's talk about the extension types. You can use them flexibly. You can leave a message on the public account CodeL to obtain related resources or ask other questions.

 

Related Article

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.