.NET 2008中的新方法——扩展属性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;//正则表达式的空间
namespace Tools
{
public static class SelfControl //这个类为static的,在静态类中是不能定义非静态方法的
{
/// <summary>
/// 检查字符串是否为Email格式的地址
/// </summary>
/// <param name="EmailAddress">Email格式字符串</param>
/// <returns>true为email格式的,false不是邮件格式的</returns>
public static bool IsEmail(this string EmailAddress)//这个方法所以也只能为静态方法
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(EmailAddress);
}
}
}
注意这里方法上使用了关键字 this ,所以我们可以这么使用这个方法using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;//正则表达式的空间
namespace Tools
{
public static class SelfControl //这个类为static的,在静态类中是不能定义非静态方法的
{
/// <summary>
/// 检查字符串是否为Email格式的地址
/// </summary>
/// <param name="EmailAddress">Email格式字符串</param>
/// <returns>true为email格式的,false不是邮件格式的</returns>
public static bool IsEmail(this string EmailAddress)//这个方法所以也只能为静态方法
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(EmailAddress);
}
}
}
string myEmail=" Caceolod_1999@hotmail.com"
myEmail.IsEmail() -----------返回true
灵活应用 我们可以定义一个方法 public static string GetStr(this string Str,int BeginIndex,int EndIndex);
如果我们定义了一个这样的方法,那么我们就可以这样调用
string myStr ="I'm a Example of .NET";
string myStr1 = myStr.GetStr(2,5) ----------这样我们得到字符串mystr的第三个到第六个的字符组成的字符串。
小记:.net3.0中的扩展方法在使用效果上看,几乎与javascript中的prototype如出一辙,javascript中如果在String的prototype原型上定义了某个方法,会使所有String的实例都能直接使用该方法,参看以下js代码
<script type="text/javascript">
String.prototype._IsNull = function()
{
return (this==""||this==null||this=="undefined");
}
var s="";
document.write(s._IsNull())
</script>
String.prototype._IsNull = function()
{
return (this==""||this==null||this=="undefined");
}
var s="";
document.write(s._IsNull())
</script>

浙公网安备 33010602011771号