扩展方法 (
Extension Methods) 我们平时在使用要判断一个字符串是不是邮件地址的,以前的写法:
public
bool
isEmailAddress(
string
email)
{
Regex regex = new Regex(
@"^[/w-/.]+@([/w-]+/.)+[/w-]{2,4}$"); return regex.IsMatch(email);
}
使用:
bool
isEmail
=
isEmailAddress(
"
abc@abc.com
"
);
在新特性中,我们可以为各种数据类型增加一些方法
//
下面代码为string添加IsValidEmailAddress()方法
public
static
class
ScottGuExtensions
//
强调必须是static类
{
public static bool IsValidEmailAddress(
this string s) //参数写法 this 类 类对象
{
Regex regex = new Regex(
@"^[/w-/.]+@([/w-]+/.)+[/w-]{2,4}$"); return regex.IsMatch(s);
}
}
使用:只要引用命名空间即可使用扩展方法 在任何地方的字符串都出现
IsValidEmailAddress方法
"abc@abc.com".IsValidEmailAddress(); 像我在写LinQ的第一节的时候,判断一个数是不是偶数,可以写成扩展方法如:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)