What is the extension method for a class
Extension methods enable you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type.
Msdn
Extension methods enable you to ' add ' methods to existing types without creating a new derived type, recompiling, or other Wise modifying the original type. Extension methods is a special kind of static method, but they is called as if they were instance methods on the Extende D type.
In the traditional mode, if you want to add an extra custom special logic to a type (class), or a new business method, you have to redefine a type to inherit the original method, with an inherited class or interface, but some are decorated with sealed, and cannot be inherited at this time. For example, string, value type, sealed decorated class.
The extension method is proposed c#3.0 this version. Solves the drawbacks of a class that must be extended by inheritance, and the most important thing is that it works well.
Usually in our use of the process is also often seen, such as this one of the method is to expand the method. Msdn
Attention:
The extension method must be defined in a non-nested, non-generic static class.
Note that it is defined inside a non-nested< non-nested >, non-generic< non-generic > static< static & Gt Class:
The rules for extension methods have the following points:
- The extension method must be defined in the static class that the extension method must be non-nested, non-generic;
- The first parameter of an extension method is decorated with the This keyword;
- The first method parameter cannot have a ref or out keyword-modified parameter;
There are two steps to calling an extension method
- The namespace of the referencing project;
- The parameters are called two kinds;
- Use <ExtendClass>.<ExtendClassMethod> (parameters, Parameters +?) As with traditional calling methods
- < parameter type >.<ExtendClassMethod> (parameter +?)
Application of Advanced Point binding extension method at compile time <MSDN> you can use extension methods to extend a class and interface without having to rewrite them
1 //Define an interface named IMyInterface.2 namespaceDefineimyinterface3 {4 usingSystem;5 6 Publicinterface IMyInterface7 {8 //Any class that implements IMyInterface must define a method9 //That matches the following signature.Ten voidMethodB (); One } A } - - the //Define extension methods for IMyInterface. - namespaceExtensions - { - usingSystem; + usingDefineimyinterface; - + //The following extension methods can be accessed by instances of any A //class that implements IMyInterface. at Publicstaticclass Extension - { -Publicstaticvoid MethodA ( ThisIMyInterface MyInterface,inti) - { - Console.WriteLine -("Extension.methoda (This imyinterface myinterface, int i)"); in } - toPublicstaticvoid MethodA ( ThisIMyInterface MyInterface,strings) + { - Console.WriteLine the("Extension.methoda (This imyinterface myinterface, string s)"); * } $ Panax Notoginseng //This method was never called in ExtensionMethodsDemo1, because each - //Of The three classes A, B, and C implements a method named MethodB the //That has a matching signature. +Publicstaticvoid MethodB ( Thisimyinterface MyInterface) A { the Console.WriteLine +("Extension.methodb (This imyinterface myinterface)"); - } $ } $ } - - the //Define Three classes that implement IMyInterface, and then use them to test - //The extension methods.Wuyi namespaceExtensionMethodsDemo1 the { - usingSystem; Wu usingExtensions; - usingDefineimyinterface; About $ classA:imyinterface - { -Publicvoid MethodB () {Console.WriteLine ("A.methodb ()"); } - } A + classB:imyinterface the { -Publicvoid MethodB () {Console.WriteLine ("B.methodb ()"); } $Publicvoid MethodA (inti) {Console.WriteLine ("B.methoda (int i)"); } the } the the classC:imyinterface the { -Publicvoid MethodB () {Console.WriteLine ("C.methodb ()"); } inPublicvoid MethodA (Objectobj) the { theConsole.WriteLine ("C.methoda (Object obj)"); About } the } the the classExtmethoddemo + { -Staticvoid Main (string[] args) the {Bayi //Declare An instance of class A, Class B, and Class C. theA A =NewA (); theb b =NewB (); -c C =NewC (); - the //For A, B, and C, call the following methods://--MethodA with an int argument//--MethodA with a string argument//--MethodB with no argument.//A contains no MethodA, so all call to MethodA resolves to//The extension method, which has a matching signature. theA.methoda (1);//Extension.methoda (object, int) theA.methoda ("Hello");//Extension.methoda (object, String)//A has a method which matches the signature of the following call//To MethodB. theA.methodb ();//A.methodb ()//B have methods that match the signatures of the following//method calls. -B.methoda (1);//B.methoda (int) theB.methodb ();//B.methodb ()//B have no matching method for the following call, but//class Extension does. theB.methoda ("Hello");//Extension.methoda (object, String)//C contains an instance method, matches each of the following//method calls. theC.methoda (1);//C.methoda (object)94C.methoda ("Hello");//C.methoda (object) theC.methodb ();//C.methodb () the } the }98 } About /*Output: - Extension.methoda (This imyinterface myinterface, int i)101 Extension.methoda (This imyinterface myinterface, string s)102 A.methodb ()103 B.methoda (int i)104 B.methodb () the Extension.methoda (This imyinterface myinterface, string s)106 C.methoda (Object obj)107 C.methoda (Object obj)108 C.methodb ()109 */
The compiler is how the C # 3.0 compiler discovers the extension method when it sees the invocation usage of a class, first from an instance method of the class, if no instance method with the same name as the calling method is found, and then finds the appropriate extension method from all imported namespaces. and match the variable type to the extension type. This is only our understanding is such a process, if in the same namespace, the compiler will directly use the current namespace corresponding to the matching method, let me look at the next ILDasm.exe. If the namespace of the same assembly is not the same, it can be seen in the manifest manifest file.
Summary of results
Method is an instance method of the call order type---> extension methods under the current namespace---> Other namespace extension methods that are imported.
Raise questions
NullReferenceException exception is thrown when an instance method or a static method is called on a null reference? Does an exception occur when the class calls an extension method? (Do not use some of the properties or methods in the class to emphasize invocation)
public static void Nulluse (this testextend sextend) {Console.WriteLine ("NUll used Method"); } parsing: Defining an extension method on an empty type does not appear NullReferenceException, it just passes the null reference as a parameter to the static method.
Extension methods |
Static methods |
Testextend Sextend=null; Sextend.nulluse (); |
Testextend Sextend=null; Nulluse. (Sextend); |
From ILDASM we can see the correctness of our conjecture notice
Problems that may be caused by sub-class contamination such as
public static bool IsNull (thisObjectSTR) {return str = = NULL; }
You would have only wanted to extend the method of testextend this class, because you want to use the extension result of isnull this type to pass in the parameter (object), the result causes all object types to extend this method, this has the terrible consequence.
So when you extend a method of a type, you extend from the OK type. Try to avoid extending from the parent class.
There is something wrong or wrong place to hope that everyone to correct, thank you
My development environment is VS2015
Demo Download "Http://pan.baidu.com/s/1bY51P8"
c#3.0 extension Method Learning Chapter