C # Literacy: it helps you master C #'s extension methods and explore the nature and precautions of extension methods,

Source: Internet
Author: User

C # Literacy: it helps you master C #'s extension methods and explore the nature and precautions of extension methods,
1. Why do I need extension methods?

 

. NET3.5 provides us with the concept of extension methods,Its function allows you to add new methods to a class or structure without modifying the original structure of the type to be added.

Thinking: Why do we need to extend the method? Why don't we directly modify the original type?

First, assume that there is a class in our project. After a while, we clearly know that we need to add a new function for this class. There are two solutions to this requirement:

(1) directly modify the definition of the current class

The disadvantage of doing so is that the backward compatibility is broken, and the old code used earlier may not be compiled. For example, the old Code uses a Methed (int, int) method, but to meet the new function, we have now modified it to Methed (int, int, int), adding another parameter, in this way, the original Old Code cannot be compiled.

(2) derive from the current class as the base class and implement it in the subclass.

This method also has a disadvantage, that is, if the function needs to be modified, we need to maintain two places, one is the parent class and the other is the subclass, which increases the code maintenance workload.

At this time, the new feature extension method solves the above two problems, and also solves the problem that when some classes are implemented by a third party, we cannot modify the source code, and some classes cannot be inherited, cannot be derived. In either case, you can use the extension method to add new features. With the extension method, you can modify the type without creating a subclass or directly modifying the type.

 

2. How to Use the Extension Method

 

2.1 rules

Defining extension methods must follow twoStaticAnd oneThis:

1. Extension methods must be defined in static classes, and each extension method must also be declared as static
2. All extension methods must use the this keyword to modify the first parameter.
 

 

As shown in the implementation of the extension method, we need to extend a function for the StringBuilder system type to extract the index of a character in a string object.


 

2.1 call the extension method at the instance level

Calling an extension method at the instance level means that the call is performed on the instance of the extended object instead of using the static class call we have defined. For details about how to call it, please refer to the code.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace ExStensionMethd {class Program {static void Main (string [] args) {StringBuilder tmpStr = new StringBuilder ("12323"); Console. writeLine (tmpStr. stringIndef ('2'); // here we use the tmpStr instance of StringBuilder to directly call the Console. readKey () ;}/// <summary> // static class of the Extension Method /// </summary> static class ExtionClass {public static int StringIndef (this StringBuilder str, char tmpChar) {int index = 0; for (; index <str. length; index ++) {if (str [index]. equals (tmpChar) {return index ;}} return-1 ;}}}Instance hierarchical call extension method

Note: The extension method can have multiple parameters,However, the position of the first parameter is always an extension object and cannot be changed. That is to say, only the first parameter can be modified with the this keyword.Other parameters are considered as common parameters of the method.

 

3. Define the location of the Extension Method

When defining the extension method, that is, when defining the extension method static class, we must specify a namespace for it. If the namespace is different from the namespace for using the extension method, you need to import the namespace (using the using Keyword ). We recommend that you define the extension method as the same namespace of the type to be extended. For example, the namespace of the System type StringBulder in the above example is System. text, we can add a new class, and then define the namespace as System. text, that is, it is better to have a global namespace with the outermost layer. The benefits of doing so are described below.

 

4. Nature of extension methods

 

The essence of the extension method is actually implemented by the compiler using the image principle, without changing the original type or appending anything else, and viewing the IL code after the translation is generated, we can see the address marked in red, call int32 ExStensionMethd. extionClass: StringIndef (class [mscorlib] System. text. stringBuilder, char) is actually calling the public static method of the original static class.


 


So in the codeTmpStr. StringIndef ('2') and ExtionClass. StringIndef (tmpStr, '2 ')Is equivalentBut why can we use instance calls directly? This is because the compiler does the work silently.

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

TmpStr. StringIndef ('2 ')

When you see the following code during compilation, the compiler will work in two steps:

(1) The Compiler checks the current tmpStr type, that isStringBulder class andStringBulder any base classWhether the matched function named StringIndef contains a char parameter is available. If it is found, the IL code is generated and it is called;

(2) If no matching method is found, check whether any static class defines a static method named StringIndef, and the first parameter of this method must be modified with the this keyword, the parameter type is StringBulder. Generate the corresponding IL code to call it when you find it.

Therefore, this is exactly what we define the extension method, because the compiler is based on rules to match the corresponding method to generate the IL code for it. However, even if we define the extension method, other programmers do not know. Isn't that an alternative. As a powerful compiler for the universe VS, it uses"Smart sensing"To simplify our use of the extension method, when we use the extension type instance, when the dot is pressed, VS automatically adds the Extension Method for us to choose, for our programmers, it is like directly using the original method of the extension object. This is what VS compiler does for us.

 

5. Extend various types using extension methods

 

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

Class Program {static void Main (string [] args) {"123123123123 ". showItems (); // string new [] {1, 2, 3, 4 ,}. showItems (); // int array new List <int> {1, 2, 3, 4 }. showItems (); // List container Console. readKey ();}} /// <summary> /// static class of the Extension Method /// </summary> static class ExtionClass {public static void ShowItems <T> (this IEnumerable <T> colletion) {foreach (var item in colletion) {if (item is string) Console. writeLine (item); else Console. writeLine (item. toString ());}}}Interface Extension Method

 

6. Notes for using extension methods

 

  • C # extension methods are supported. extended attributes, extended events, and extension operators are not supported;
  • Extension classes must be defined in non-generic static classes. They cannot be generic classes. extension class names can be defined at will. [Why cannot it be a generic static class? If you really don't know, it means that you didn't take a closer look at the compile content, because the extension method is actually the matching and compilation at compilation, generic classes can be determined only at runtime, so they cannot be generic static classes ];
  • The extension method must have a file scope, that is, it must be defined directly under a namespace in the file and cannot be defined in another class;
  • Multiple Static classes can define the same extension method. Therefore, you must call the object explicitly. When a call conflict occurs, you cannot use an instance call. Only static classes and methods can be used in normal ways;
  • If the extended class is a base class and has many derived classes, Its Derived classes also have this extended method (just like the interface we expanded above ), this has the advantage and disadvantage. The advantage is that sub-classes can use this method. The disadvantage is that smart prompts will recursively go down and there will be a lot of garbage information filled;
  • There is a version issue with the extension method. As we mentioned earlier, during compilation, we will first find out whether this class has defined a matching method, and then go back to the static class. So if we now define an IndexOf method, and in a later version of Microsoft, the same IndexOf method is officially added, our static method will not be called.




References: proficient in C # (version 6th)

CLR via C # (version 4th)

Due to the knowledge of this talent, it is inevitable that the description is missing. If you have any mistakes, please note. What!



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.