C # extension method instance in ASP.net

Source: Internet
Author: User
Tags datetime extend instance method numeric numeric value static class

This is what MSDN says, that is, you can add one or more methods to these types based on string,int,datarow,datatable, and you don't need to modify or compile the code for the type itself when you use it.

As an example, take string as an example, and add a function that converts a string to a numeric value in the string type.

In the past we might have done it, and would have written a method to do the conversion

public static int Strtoint (string s) {int id; Int. TryParse (s, out ID);//Here returns the ID of 0 return ID when the conversion fails; }

Call is used

string s = "abc"; int i = Strtoint (s);

If the string type has a method named ToInt (), which converts from a string to a numeric value, you can call the

? string s = "abc"; int i = S.toint ();

This looks is not better, below to see how to achieve the specific

First step:

I first create a solution, a Web application (webtest), and a class library (W.common)

Add a reference W.common project to the WebTest project

Step Two: Create a new EString.cs class in the class library

The code is as follows Copy Code

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace W.common
{
public static Class Estring
{
<summary>
Converts a string to an int
</summary>
<param name= "T" ></param>
<returns> return 0</returns> when conversion fails
public static int ToInt (This string t)
{
int id;
Int. TryParse (t, out ID);//Here The ID of 0 is returned when the conversion fails
return ID;
}
}
}

Look at the code above, the extension method stipulates that the class must be a static class, Estring is a static class, all the methods contained in it must be static methods.

MSDN is the way to specify extension methods: "Extension methods are defined as static methods, but they are invoked through instance method syntax." Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier. ”

Estring has a toint static method, he receives a self argument this, the type string,this string must be in the first position of the method parameter.

What does this mean, that you need to extend a ToInt method to string, this is the object of string instantiation, this may not be very clear, my ability to express is weak, don't be offended ... In layman's parlance, the extension method has nothing to do with the name of a static class, simply by defining a static method within a static class, and the first argument must begin with this string.

If you want to extend the method name Isrange (to determine whether this time range) for the datetime type, the code is as follows:

The code is as follows Copy Code

<summary>
Whether this time is within the range-1: Less than start 0: In Start and end time range 1: End time Exceeded
</summary>
<param name= "T" ></param>
<param name= "StartTime" ></param>
<param name= "Endtime" ></param>
<returns></returns>
public static int Isrange (this datetime 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) to 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

The code is as follows Copy Code
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using w.common;//here refers to the namespace in which the extension method resides

Namespace WebTest
{
public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{
Use1 ();
Response.Write ("<br/>");
Use2 ();
}

<summary>
No extension method used
</summary>
private void Use1 ()
{
string s = "abc";
int i = Strtoint (s);
Response.Write ("No extension method:" + i);
}

<summary>
Using extension methods
</summary>
private void Use2 ()
{
string s = "2012";
int i = S.toint ();
Response.Write ("Use extension method:" + i);
}

public static int Strtoint (string s)
{
int id;
Int. TryParse (s, out ID);//Here the ID returned when the conversion failed is 0
return ID;
}
}
}

All right, here we go. extension methods for C # We'll talk about this, if you have a friend you don't know, you can search.

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.