什么是扩展方法,为什么我们需要使用它?
嗨,
googlin后认识了一些关于扩展方法,但不是很清楚为什么我们需要使用扩展方法,它是如何工作的?
请建议。如果你需要将功能添加到第三方.dll文件或者你没有源代码的直接访问某个组件
感谢,
Subhen
什么是扩展方法?
参考这个问题 - 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));
哪一个更流利,更可读?带扩展方法的那个。
扩展方法是有用的。
因此,例如,您不能直接访问修改String类,但使用扩展方法可以向其中添加方法。 (或给该类用户留下印象)
不,这是不正确的。 – 2010-07-21 09:21:27
是的,这是真的。我认为将功能添加到没有源代码访问权限的第三方组件可能会很有用......是否正确? – 2010-07-21 09:24:35
绝对错误。你永远不能改变任何类型的东西,你只能用实例来玩,这就是扩展方法的作用。他们只是玩与实例不同的类型。 – 2010-07-21 09:28:07
扩展方法只是增加了一点“语法糖”,使编写代码更容易。
例如,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))
这个有问题,如果字符串没有找到,你会得到一个例外。而开发者很懒。所以如果他们认为,这不会发生,他们只是不抓住它或重构所有occourances。所以,你可以在某个地方制作一个方法。
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);
}
}
...然后是硬的部分。发送一封电子邮件给所有开发者,这个现在已经存在,并且他们将来会使用它。并把它放入文档,新的开发者...或:
只需添加一个“本”在像
public static string SubstringTill(this string input, string till, StringComparison comparisonType = StringComparison.CurrentCulture)
的方法,你会得到一个扩展方法。当有人编写代码,并且需要这样的代码时,他看到了呃,这样做的人已经完成了一种方法。所以可重用性和DRY更容易实现。如果它正确地记录了它的作用,以及可能发生的例外情况。
精确重复:http://stackoverflow.com/questions/403539/what-are-extension-methods – Krunal 2010-07-21 09:10:03
你也可以检查http://stackoverflow.com/questions/487904/what-advantages-of-extension-方法,你找到了 – Krunal 2010-07-21 09:15:40