C# - 重载扩展方法
在一个非常基本的学习练习中,我使用了 LinkedList,当需要返回最后一个元素时,我错误地使用了方法 Last() 而不是属性 Last,然后我开始怀疑。
该方法是 IEnumerable 的扩展方法,因此如果不重载(Visual Studio + Resharper 向我显示该方法的基本 IEnumerable 扩展方法签名),效率将非常低。
LinkedList MSDN 页面 将大多数扩展方法指定为“重载”。但我不确定这意味着什么(单击方法链接会显示基本方法的解释)以及为什么 Visual Studio + Resharper 不向我显示它。
谢谢。
In a pretty basic studying exercise I was using LinkedList and when needed to return the last element I mistakingly used the method Last() instead of the property Last and then I started to wonder.
This method is an extension method of IEnumerable, so if it's not overloaded (Visual Studio + Resharper are displaying me the basic IEnumerable extension method signature for this method), It would be very inefficient.
The LinkedList MSDN page specifies most of the extension methods as "Overloaded." but I'm not sure what it means(clicking a method link displays the basic method's explanation) and why doesn't Visual Studio + Resharper show it to me.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个很容易犯的错误就是将重载和覆盖相混淆。当 MSDN 页面说方法重载时,意味着该方法有多个版本,并且具有不同的参数。
您不能覆盖扩展方法,因为它们是静态的。
An easy mistake to make is to confuse overloading with overriding. When the MSDN page is saying that the methods are overloaded, it means that there are multiple versions of the methods with different parameters.
You cannot override extension methods since they are static.
从技术上讲,您无法“覆盖”扩展方法,因为它们是静态的。但是,如果类或接口上的方法与扩展方法具有相同的签名,则编译器将优先选择类或接口方法而不是扩展方法。因此,通常以下行:
... 实际上会编译为:
但在以下代码中:
编译器实际上将调用
LinkedList2.LastOrDefault()
而不是Enumerable.LastOrDefault;(此 IEnumerable)
。然而,由于 LinkedList 没有
Last()
或LastOrDefault()
方法,因此您最终会调用效率极低的Enumerable.Last()
You cannot technically "override" extension methods, because they are static. However, if a method on your class or interface has the same signature as an extension method, the compiler will prefer the class or interface method over the extension method. So normally the following line:
... would actually be compiled as:
But in the following code:
The compiler is actually going to call
LinkedList2.LastOrDefault()
instead ofEnumerable.LastOrDefault<T>(this IEnumerable<T>)
.Because LinkedList does not have a
Last()
orLastOrDefault()
method, however, you would end up calling the highly-inefficientEnumerable.Last()