读书人

c# 3.5以下的扩展类学习

发布时间: 2012-12-19 14:13:14 作者: rapoo

c# 3.5以上的扩展类学习
今天在一个群中看到人家说,c#3.5以上中,有个叫扩展方法的东西,于是看了下,
原来大概是这样:

比如,我们传统的情况下,要检验一个EMAIL是否合法,可能要这样写:
string email = Request.QueryString["email"];

if ( EmailValidator.IsValid(email) ) {

}

这里用到了一个工具类,自己编写的,而现在可以这样了,直接
string email = Request.QueryString["email"];

if ( email.IsValidEmailAddress() ) {

}
其实这里是直接扩展了string 类中,为其增加了新的方法,但却没更改string类中的代码和编译了其中的代码!,这样做:
public static class Test{
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
}
增加静态类和增加静态方法,这样就可以了,注意其中
public static bool IsValidEmailAddress(this string s)
中的this,意思是告诉编译器,针对string进行扩展,
使用的时候,很简单,只需要using Test;
这样就可以实现了.

更多的应用请参考:
http://www.cnblogs.com/ldp615/archive/2009/08/07/1541404.html

读书人网 >C#

热点推荐