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.
publicstatic int StrToInt(string s){ int id; int.TryParse(s, out id);//这里当转换失败时返回的id为0 returnid;} |
Calls are used
strings = "abc";inti = StrToInt(s); |
if the string type has a method named ToInt () (from a string to a numeric value) , you can call the
strings = "abc";inti = 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{ publicstaticclassEString { /// <summary> /// 将字符串转换为Int /// </summary> /// <param name="t"></param> /// <returns>当转换失败时返回0</returns> publicstaticintToInt(thisstringt) { intid; int.TryParse(t, outid);//这里当转换失败时返回的id为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, thisis 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> /// 此时间是否在此范围内 -1:小于开始时间 0:在开始与结束时间范围内 1:已超出结束时间 /// </summary> /// <param name="t"></param> /// <param name="startTime"></param> /// <param name="endTime"></param> /// <returns></returns> public staticintIsRange(thisDateTime t, DateTime startTime, DateTime endTime) { if(((startTime - t).TotalSeconds > 0)) { return-1; } if(((endTime - t).TotalSeconds < 0)) { return1; } return0; } |
The extension method here starts with this datetime, so you can call the
time.IsRange(t1,t2);//判断时间time是否在t1到t2的范围内 |
The current code needs to refer to the namespace before using the extension method
usingSystem;using System.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingW.Common;//这里引用扩展方法所在的命名空间namespacewebtest{ publicpartialclass_Default : System.Web.UI.Page { protectedvoidPage_Load(objectsender, EventArgs e) { use1(); Response.Write("<br />"); use2(); } /// <summary> /// 没有用扩展方法 /// </summary> privatevoiduse1() { strings = "abc"; inti = StrToInt(s); Response.Write("没有用扩展方法:"+ i); } /// <summary> /// 使用扩展方法 /// </summary> privatevoiduse2() { strings = "2012"; inti = s.ToInt(); Response.Write("使用扩展方法:" + i); } publicstaticintStrToInt(strings) { intid; int.TryParse(s, outid);//这里当转换失败时返回的id为0 returnid; } }} |
Understanding of C # extension methods