【发布时间】:2010-07-21 09:08:32
【问题描述】:
【问题讨论】:
【问题讨论】:
什么是扩展方法?
参考这个问题-What are Extension Methods?
为什么我们需要使用它?
Somehow, I don't agree to the idea of using extension methods to extend an existing type since practically this is impossible. 要使用扩展方法的唯一原因是在任何类型上都带上fluency and readabilty。
检查此代码..
string str = "Hello world";
string result = Helper.Method2(Helper.Method1(str));
这个带有扩展方法的代码可以写成如下。
string str = "Hello world";
string result = str.Method1().Method2();
//compiler ultimately compiles this code as Helper.Method2(Helper.Method1(str));
哪一个更流畅易读?具有扩展方法的那个。
【讨论】:
扩展方法允许您向现有类型添加方法,而无需创建派生类。当您无法访问框架等代码时,它也很有用。更多信息here
【讨论】:
如果您需要向第三方 .dll 或您无法直接访问源代码的某些组件添加功能,扩展方法会很有用。
因此,例如,您无法直接访问修改 String 类,但您可以使用扩展方法向其添加方法。 (或者给类的用户那种印象)
【讨论】:
扩展方法只是添加一点“语法糖”,使编写代码更容易。
例如,IEnumerable<T> 接口上有很多扩展方法。其中一些是在名为EnumerableExtensions 的静态类中定义的,可能是这样的:
public static class EnumerableExtensions
{
public static IEnumerable<T> Where<T>(this IEnumerable<T> items, Expression<Func<T, bool>> predicate)
{
// Filter based on the predicate and return the matching elements
}
}
请注意,类和方法都标记为static,并且在第一个参数前面有一个this 关键字。 this 将此方法标记为扩展方法。
现在,要在IEnumerable<T> 的实例上使用此方法,比如myTees,您只需键入
var filtered = myTees.Where(t => t.IsCool);
但这并不是实际编译到 .dll 中的代码。编译器将这个对扩展方法的调用替换为对
的调用var filtered = EnumerableExtensions.Where(myTees, t => t.IsCool);
如您所见,它只是另一个类的常规静态方法。
所以,扩展方法的一个要点是让静态方法的使用更加流畅,生成更易读的代码。
当然,这也产生了您可以在 .NET 框架中扩展 任何 类型的效果 - 甚至(尤其是)不是您自己创建的类型!这就像编写一个常规静态方法一样简单,该方法将您要扩展的类型作为第一个参数,在其前面加上this 并标记包含类static。苹果派送上来了! =)
【讨论】:
它们允许您使用新方法扩展所有现有的类。无需更改其代码或 Dll。
好处是,它们是有意使用的。
例如:假设您在项目中经常需要剪切字符串,直到找到特定的字符串。
通常你会这样写代码:
input.Substring(0,input.LastIndexOf(tofind))
这有一个问题,如果没有找到字符串,你会得到一个异常。开发人员很懒惰。所以如果他们认为这不会发生,他们只是没有抓住它或重构所有的事件。所以,你可以在某个地方创建一个方法。
public static class StringExtensions
{
public static string SubstringTill(string input, string till, StringComparison comparisonType = StringComparison.CurrentCulture)
{
int occourance = input.LastIndexOf(till, comparisonType);
if (occourance < 0)
return input;
return input.Substring(0, occourance);
}
}
然后...然后是困难的部分。向所有开发人员发送一封电子邮件,告诉他们现在已经存在,并且他们将来应该使用它。并将其放入新开发人员的文档中......或者:
只需在方法中添加一个“this”即可
public static string SubstringTill(this string input, string till, StringComparison comparisonType = StringComparison.CurrentCulture)
你得到一个扩展方法。当任何人编写代码并且需要这样的代码时,他会看到,呃,已经有一种方法由某人完成。因此可重用性和 DRY 更容易实现。如果它正确记录了它的作用,以及可能发生的异常。
【讨论】: