C # Extension methods

Source: Internet
Author: User
Tags time 0

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

strings = "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 s = "abc";
int i = S.toint ();

The first step: This looks better, let's see how it's done.

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, 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>   ///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);//判断时间time是否在t1到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; }    }}

C # Extension methods

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.