为什么 C# 类库中需要扩展方法

发布于 12-24 17:00 字数 192 浏览 2 评论 0原文

我确实浏览了一些 MSDN 文档。我发现扩展方法也记录在那里。

我不明白,为什么这些基类库有扩展方法?什么时候可以将它们添加到特定的类库本身?

优点是什么?不同之处 ?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

征棹2024-12-31 17:00:24

请注意,其中许多方法都在接口上运行,这是使用扩展方法的完全合法的借口,即使对于 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.

情释2024-12-31 17:00:24

顾名思义,扩展方法扩展了目标类型的功能或可用性。

  1. 这些方法可以在类型发布后(在类型创作时间之前)添加。
  2. 它们可以由不同的人编写
  3. 扩展方法可以针对接口。 (替代方案是拥有一个具有这些方法的通用基类型,或者在每种类型中重新实现它们)
  4. 不同的人可以根据自己的需要以不同的方式扩展相同的类型。

正确使用扩展方法可以消除实际类型定义/实现中的正交混乱(而不是关注类型定义中类型的核心功能)。

以 LINQ 为例 - 通过为 IEnumerable 提供扩展方法,它可以针对大量已发布的类型(以及将来可能编写的大量类型);它分离了正交关注点,例如查询类型与实际类型。

Extension methods as name suggests extends the functionality or usability of the target type.

  1. These methods can be added later (than type authoring time) after type has already been published.
  2. They can be written by different group of people
  3. Extension methods can target interfaces. (Alternative would have been to have a common base type having these methods or re-implementing them in each type)
  4. Different people can extend the same type differently as per their needs.

Correct use of extension methods can remove orthogonal clutter from the actual type definition/implementation (instead focusing of the core functionality of the type within type definition).

Take example of LINQ - by providing extension methods to IEnumerable, it could target vast number of already published types (and vast number of types that may written in future); it has separated orthogonal concern such as querying the type from the actual type.

晨光如昨2024-12-31 17:00:24

记录的扩展方法在 IEnumerable 上定义,由 ObjectSet 实现。

它们已被记录下来,因此您知道可以使用它们。

作为扩展方法,它们最终免费扩展实现此接口的任何类型。

The extension methods documented are defined on IEnumerable<T>, which ObjectSet<T> implements.

They are documented so you know you can use them.

As extension methods they end up extending any type implementing this interface, for free.

遥远的绿洲2024-12-31 17:00:24

我认为这很可能是一个“营销问题”。建议 BCL 消费者(我们)在需要时使用扩展方法的方式。

从可用性的角度来看,在我看来,将它们集成到 BCL 中没有任何好处

I think it's most probbably a "marketing issue". The way to advise to BCL consumer (us) to use Extension methods, where we need them.

From the usability perspective, there is no any goodness, imo, of integrating them in BCL

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文