什么是扩展方法? [英] What are Extension Methods?
问题描述
什么是.NET扩展方法?
编辑: 我已经发布的后续问题,在扩展方法 用法
扩展方法允许开发者添加新的方法向公众 现有的CLR类型的合同, 而无需子类,或 重新编译原来的类型。
扩展方法帮助交融 的鸭打字支持的灵活性 动态语言在当今流行 与性能和编译时 强类型的验证 语言。
参考:<一href="http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx" rel="nofollow">http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx
下面是一个扩展方法的样本(注意这
关键字盈方的第一个参数):
公共静态布尔IsValidEmailAddress(这个字符串s)
{
正则表达式的regex =新的正则表达式(@^ [\ W - \。] + @([\ w - ] + \)+ [\ w - ] {2,4} $);
返回regex.IsMatch(多个);
}
现在,上面的方法,可直接从任何字符串调用,像这样的:
BOOL的isValid =so@mmas.com.IsValidEmailAddress();
然后添加的方法也将出现在智能感知:
至于实际使用的扩展方法,你可以添加新的方法到类没有派生新类。
看看下面的例子:
公共类扩展{
公众诠释总和(){
返回7 + 3 + 2;
}
}
公共静态类扩展{
公共静态持股量平均(这个扩展extnd){
返回extnd.Sum()/ 3;
}
}
正如你所见,类扩展
是加入了一个名为方法平均上课扩展
。为了获得平均,你叫平均
的方法,因为它属于扩展
类:
扩展EX =新的扩展();
Console.WriteLine(ex.average());
参考:<一href="http://aspguy.word$p$pss.com/2008/07/03/a-practical-use-of-serialization-and-extension-methods-in-c-30/" rel="nofollow">http://aspguy.word$p$pss.com/2008/07/03/a-practical-use-of-serialization-and-extension-methods-in-c-30/
What are extension methods in .NET?
EDIT: I have posted a follow up question at Usage of Extension Methods
Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type.
Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.
Reference: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx
Here is a sample of an Extension Method (notice the this
keyword infront of the first parameter):
public static bool IsValidEmailAddress(this string s)
{
Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
return regex.IsMatch(s);
}
Now, the above method can be called directly from any string, like such:
bool isValid = "so@mmas.com".IsValidEmailAddress();
The added methods will then also appear in IntelliSense:
As regards a practical use for Extension Methods, you might add new methods to a class without deriving a new class.
Take a look at the following example:
public class Extended {
public int Sum() {
return 7+3+2;
}
}
public static class Extending {
public static float Average(this Extended extnd) {
return extnd.Sum() / 3;
}
}
As you see, the class Extending
is adding a method named average to class Extended
. To get the average, you call average
method, as it belongs to extended
class:
Extended ex = new Extended();
Console.WriteLine(ex.average());
这篇关于什么是扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!