当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > C#之 VS2008 之 Extension Methods

ASP.NET
Asp.Net 通用数据操作类 (附通用数据基类)
asp.net汉字转拼音和获取汉字首字母的代码
asp.net 多字段模糊查询代码
OpenCms 带分页的新闻列表
URLRewriter最简单入门介绍 URLRewriter相关资源
asp.net Repeater取得CheckBox选中的某行某个值
asp.net清空Cookie的两种方法
asp.net一些很酷很实用的.Net技巧
asp.net生成高质量缩略图通用函数(c#代码),支持多种生成方式
asp.net TripleDES加密、解密算法
Asp.net中防止用户多次登录的方法
asp.net Repeater取得CheckBox选中的某行某个值的c#写法
asp.net DataGridView导出到Excel的三个方法[亲测]
C#,winform,ShowDialog,子窗体向父窗体传值
asp.net学习中发现的比较完整的流程
ASP.net 页面被关闭后,服务器端是否仍然执行中?
asp.net Context.Handler 页面间传值方法
asp.net xml序列化与反序列化
asp.net实例代码protected override void Render(HtmlTextWriter writer)
asp.net(c#)捕捉搜索引擎蜘蛛和机器人

ASP.NET 中的 C#之 VS2008 之 Extension Methods


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 135 ::
收藏到网摘: n/a

  C#之 VS2008 之 Extension Methods。这功能让我激动不已。它可以为某一类型的变量(如string,int等)添加上我们自己增加的一些“额外”的方法,比如我们自己为一string 类型的的变量strEmail添加上一个IsValidEmailAddress方法,怎么样?这个方法是否心动?原来我们要实现这个功能着实是会费一番功夫,可是如今有了Extension Methods,很简单即可搞定它:

  方法如下:

  新添加一个静态类,比如代码为:

1using System;
  2using System.Data;
  3using System.Configuration;
  4using System.Linq;
  5using System.Web;
  6using System.Web.Security;
  7using System.Web.UI;
  8using System.Web.UI.WebControls;
  9using System.Web.UI.WebControls.WebParts;
  10using System.Web.UI.HtmlControls;
  11using System.Xml.Linq;
  12using System.Text.RegularExpressions;
  13
  14/**//// 
  15/// Summary description for MyStaticExtension
  16/// 
  17public static class MyStaticExtension
  18{
  19 public static bool IsValidEmailAddress(this string strEmail)
  20 {
  21 Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
  22 return regex.Match(strEmail).Success;
  23 }
  24
  25 public static bool IsBiggerThan10(this int intNumber)
  26 {
  27 if (intNumber > 10) return true;
  28 return false;
  29 }
  30}

  在这个类中有两个静态的方法,其中一个是IsValidEmailAddress(this string strEmail),另外一个是IsBiggerThan10(this int intNumber);

  注意这两个方法均是静态的,而且你注意到了么,它的参数前都有一个this关键字来修饰,这就是告诉编辑器,要将string类型的变量加上该IsValidEmailAddress方法,将int类型的变量加上IsBiggerThan10的方法。OK,既然准备好了,我们就开始使用它:

  首先,因为我们在该工程中只用到了一个命名空间,所以你在使用它的类中可以using MyStaticExention,也可以不using,二者均可

  然后我们就可以直接在类中使用了:

  1 string strEmail = "aa";
  2 strEmail.IsValidEmailAddress();
  1 int a = 10;
  2 bool bl = a.IsBiggerThan10();

  这个功能真让人振奋!