为什么 C# 类库中需要扩展方法
I did go through some MSDN documentations. I found extension methods also documented there.
I didn't understand, why these base class libraries have extension methods? when they could have been added to that particular class library itself?
what is the advantage? difference ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
情释2024-12-31 17:00:24
顾名思义,扩展方法扩展了目标类型的功能或可用性。
- 这些方法可以在类型发布后(在类型创作时间之前)添加。
- 它们可以由不同的人编写
- 扩展方法可以针对接口。 (替代方案是拥有一个具有这些方法的通用基类型,或者在每种类型中重新实现它们)
- 不同的人可以根据自己的需要以不同的方式扩展相同的类型。
正确使用扩展方法可以消除实际类型定义/实现中的正交混乱(而不是关注类型定义中类型的核心功能)。
以 LINQ 为例 - 通过为 IEnumerable
提供扩展方法,它可以针对大量已发布的类型(以及将来可能编写的大量类型);它分离了正交关注点,例如查询类型与实际类型。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
请注意,其中许多方法都在接口上运行,这是使用扩展方法的完全合法的借口,即使对于 Microsoft 来说也是如此,因为接口本身不能有任何方法的实现。
Note, that many of the these methods operates on Interfaces, which is a perfectly legitimate excuse of using Extension Methods, even for Microsoft since interfaces themselves can't have any implementation of methods.