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

ASP.NET
FreeTextBox(版本3.1.6)在ASP.Net 2.0中使用方法
.NET 常用功能和代码小结
在 .NET Framework 2.0 中未处理的异常导致基于 ASP.NET 的应用程序意外退出
asp.net IList查询数据后格式化数据再绑定控件
asp.net sql存储过程
asp.net 简单实现禁用或启用页面中的某一类型的控件
asp.net(c#)获取内容第一张图片地址的函数
The remote procedure call failed and did not execute的解决办法
ASP.NET 在线文件管理
asp.net 读取并修改config文件实现代码
ASP.NET Cookie 操作实现
asp.net Silverlight中的模式窗体
Silverlight中动态获取Web Service地址
asp.net Silverlight应用程序中获取载体aspx页面参数
asp.net 水晶报表隔行换色实现方法
asp.net 获取Gridview隐藏列的值
手动把asp.net的类生成dll文件的方法
asp.net 使用ObjectDataSource控件在ASP.NET中实现Ajax真分页
动态指定任意类型的ObjectDataSource对象的查询参数
asp.net Md5的用法小结

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-28   浏览: 86 ::
收藏到网摘: 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();

  这个功能真让人振奋!