如果扩展方法与密封类中的方法具有相同的签名,那么调用优先级是什么?
我正在阅读有关 C# 3.0 中的扩展方法的内容。我正在阅读的文本意味着与被扩展的类中的方法具有相同签名的扩展方法将按执行顺序排在第二位 - 也就是说,密封类中的方法被调用。如果是这种情况,如何扩展密封类?
I was reading about extension methods in C# 3.0. The text I'm reading implies that an extension method with the same signature as a method in the class being extended would be second in order of execution - that is, the method in the sealed class gets called. If this is the case, how can you extend the sealed class ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事实上,实际方法优先于扩展方法。只是为了澄清 - “执行顺序”表明两者都可以被调用; 仅原始方法会被调用。也许选择另一个名字/签名;如果您打算这样做,则不能使用扩展方法来进行猴子修补。
如果有一些基类/接口(该类型实现的)没有有此方法,您也许可以将其强制转换到那里......?
Indeed, the actual method takes precedence over the extension method. And just to make it clear - "order of execution" suggests both might be called; only the original method will be invoked. Perhaps pick another name / signature; you can't use extension methods to monkey-patch, if that is your intent.
If there is some base-class / interface (that the type implements) that doesn't have this method, you could perhaps cast it to there...?
使用另一个方法签名。扩展方法意味着您正在使用新功能扩展密封类,而不是覆盖已经实现的功能。
扩展方法对类型上的实例成员具有“按名称隐藏”语义。这意味着类型上的任何可访问实例成员将始终隐藏具有相同名称的任何扩展方法,即使扩展方法更合适。因此,如果将实例成员添加到与扩展方法同名的类型中,则扩展方法可能会变得不可调用。
欲了解更多详情,请查看这篇文章:
扩展方法最佳实践(扩展方法第 6 部分)
Use another method signature. Extension methods imply that you are extending the sealed class with new functionality and not overriding the ones already implemented.
Extension methods have "hide-by-name" semantics with instance members on a type. This means that any accessible instance member on a type will always shadow any extension methods with the same name, even if the extension method is a better fit. As a result, if an instance member is ever added to a type with the same name as an extension method, then the extension method can be rendered uncallable.
For more details, take a look at this post:
Extension Methods Best Practices (Extension Methods Part 6)