The extension method enables you to add a method to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. "This is what MSDN says, which is that you can add one or more methods based on these types of string,int,datarow,datatable and so on, without having to modify or compile the code for the type itself.
Extension methods enable you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special static method, but it can be called just like an instance method on an extended type. The above is a description of the extension method on the MSDN website, which I now illustrate with a scenario example. Suppose the main function of a console program class program{} is as follows:
Static void Main (string[] args) { = datetime.now; string time = Now. ToString ("yyyy-mm-dd hh:mm:ss"); Console.WriteLine (time); Console.readkey (); }
Assuming that the demand has changed, the date display format will be changed to "YYYY-MM-DD" format, of course, only need to initialize the time as follows:
String time = Now. ToString ("Yyyy-mm-dd");
But what if there are many classes to change the date format? Do you want to change it every time? So that once the demand has changed, it will be busy dead. The traditional solution is to encapsulate a helper class, write the method inside, and then invoke it for other classes.
In this example, the current project mimics the addition of a Datehelper class: public class datehelper{}, which defines the method within the class:
Public Static string datetostring (DateTime DT) { return dt. ToString ("yyyy-mm-dd hh:mm:ss"); }
So the original main function is rewritten as follows:
Static void Main (string[] args) { = datetime.now; string time = datehelper.datetostring (now); Console.WriteLine (time); Console.readkey (); }
At this point, if you change the requirements, you just need to rewrite the datetostring () method in the Datehelp class, no matter how many classes call this method, it will be affected. The problem is solved, but the way to invoke another class is a bit cumbersome, is there any way to make us look like now. Datetostring () as a direct call? Of course, the DateTime is written by Microsoft, we can not change, unable to create the desired instance method, so, it leads to the extension method.
Here are the elements of the extension method:
1. This method must be a static method
2. This method must be placed in a static class
3. The first parameter of this method must begin with this and specify which type the method is extended from
Based on the above elements, we datehelper class to static class: public static Classes datehelper{}, while rewriting the Datetostring () method:
Public Static string Datetostring ( this DateTime dt) { return dt. ToString ("yyyy-mm-dd hh:mm:ss"); }
Return to the main function method body and enter "now." You can see that the auto prompt has a datetostring () method, so the code can write:
Static void Main (string= DateTime.Now; string time = Now . Datetostring (); Console.WriteLine (time); Console.readkey (); }
Obviously, it's easier to use it, and it makes it seem as if it's really readable as an instance method of the extended type itself. The following summarizes the features of the extension method:
1. The extension method extends from which type, it must be a variable of this type to use, other types cannot be used, this example extends from the datetime type, can only be a variable of the datetime type. Come out (now. Datetostring ())
2. The parameter after this in the extension method is not a parameter of the method, this example is no parameter, and the DateTime DT after this is a indication of what type the extension method extends from
3. If the extension method and the instance method have the same signature, the instance method is invoked first
4. Extend the method from the parent class so that it can be used directly by the object of the class
5. Extend the method on the interface, which can be used directly by the object of the implementation class
6. The extension method is eventually compiled by the compiler: Static class. static method (), in this case, now. Datetostring () will eventually be compiled into datehelper.datetostring (now), which is the essence of it
In fact, we may encounter such a scenario, such as when the interface to extend a method, all the original implementation of the interface of the class to implement a new extension of the method, such a change is a cumbersome task, you can use the extension method "curve salvation", and sometimes we want to add a new method for a class but do not want to change the class, The way that this "pseudo-add" method of the extension method reflects its value. The most common extension method is the LINQ standard query operator, which is widely used, and this is a quick and easy way to win the code farmers to point 1024 praise.
The extension method enables you to add a method to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. ”
This is what MSDN says, which is that you can add one or more methods based on these types of string,int,datarow,datatable, using code that does not need to modify or compile the type itself.
Let's start with an example, in the case of string, you need to add a function from a string to a numeric value in the type.
In the past we might have done this, and would have written a way to do the conversion.
Public Static int Strtoint (string s) { int ID; int out ID); // here, when the conversion fails, the ID returned is 0. return ID;}
Calls are used
string " ABC " ; int i = strtoint (s);
If the string type has a method named ToInt () (from a string to a numeric value), you can call the
string " ABC " ; int i = S.toint ();
This looks better, let's see how it's done.
The first step:
I'll start by creating a solution, a Web application (webtest), and a class library (W.common)
Add a reference W.common project to a webtest project
Step Two: Create a new class named EString.cs in the class library
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text; namespacew.common{ Public Static classestring {/// <summary> ///Convert a string to an int/// </summary> /// <param name= "T" ></param> /// <returns>returns 0 when conversion fails</returns> Public Static intToInt ( This stringt) {intID; int. TryParse (T, outID);//here, when the conversion fails, the ID returned is 0.returnID; } }}
Look at the code above, the extension method specifies that the class must be a static class, Estring is a static class, and all the methods contained in it must be static methods.
MSDN defines extension methods as follows: "extension methods are defined as static methods, but they are invoked through the instance method syntax. Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier. ”
There is a toint static method in Estring, and he receives a parameter of this, the type string,this string must be in the first position of the method parameter.
What do you mean, you need to extend a ToInt method to the string, this is the object after the instantiation of string, which may not be very clear, my ability to express weak, do not take offense ah ... In layman's words, the extension method is independent of the name of the static class, and only needs to define a static method inside a static class, the first argument must begin with this string.
If you want to have the DateTime type extension method named Isrange (judging if it is within this time range), the code is as follows:
/// <summary> ///whether this time is within this range-1: Less than start time 0: Within the start and end time range 1: The end time has been exceeded/// </summary> /// <param name= "T" ></param> /// <param name= "StartTime" ></param> /// <param name= "EndTime" ></param> /// <returns></returns> Public Static intIsrange ( Thisdatetime T, datetime startTime, DateTime endTime) { if((STARTTIME-T). TotalSeconds >0)) { return-1; } if((ENDTIME-T). TotalSeconds <0)) { return 1; } return 0; }
The extension method here starts with this datetime, so you can call the
Time. Isrange (T1,T2);//Determine whether time is within the range of T1 to T2
The current code needs to refer to the namespace before using the extension method
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingW.common;//this refers to the namespace where the extension method resides namespacewebtest{ Public Partial class_default:system.web.ui.page {protected voidPage_Load (Objectsender, EventArgs e) {use1 (); Response.Write ("<br/>"); Use2 (); } /// <summary> ///no extension method is used/// </summary> Private voiduse1 () {strings ="ABC"; inti =Strtoint (s); Response.Write ("The extension method is not used:"+i); } /// <summary> ///using extension methods/// </summary>Private voidUse2 () {strings =" -"; inti =S.toint (); Response.Write ("To use the extension method:"+i); } Public Static intStrtoint (strings) {intID; int. TryParse (s), outID);//here, when the conversion fails, the ID returned is 0.returnID; } }}
The above is my understanding of the extension method and use, if there is wrong or insufficient place please correct me, thank you.
This is my first time to write an article is a row version, with a good long time ah, before all just read someone else's article, now know to write a good article really not easy ah.
Study hard and stick to your dreams.
An explanation of extension methods in C #