简体   繁体   中英

why extension methods in C# Class Libraries

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 ?

注意,许多这些方法都在Interfaces上运行,这是使用扩展方法的完全合法的借口,即使对于Microsoft也是如此,因为接口本身不能有任何方法实现。

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM