开发者

C#: Why didn't Microsoft make a ReadOnlyCollection<T> inherit from the ReadOnlyCollectionBase?

Simply put, Microsoft defined a ReadOnlyCollectionBase, yet did not use it as the base class for ReadOnlyCollection<T> when it clearly sounds that this should have been the way.

Am I missing something here? I me开发者_StackOverflowan, was there a good reason to NOT make this class the base class?


Probably because it's not generic and implements ICollection whereas ReadOnlyCollection<T> is generic and implements ICollection<T>. Note that ICollection<T> does not implement ICollection. On that topic:

ICollection<T> seems like ICollection, but it’s actually a very different abstraction. We found that ICollection was not very useful. At the same time, we did not have an abstraction that represented an read/write non-indexed collection. ICollection<T> is such abstraction and you could say that ICollection does not have an exact corresponding peer in the generic world; IEnumerable<T> is the closest.

From that same post:

ReadOnlyCollection<T> is a much better ReadOnlyCollectionBase. It’s in System.Collections.ObjectModel namespace.

Effectively, ReadOnlyCollection<T> is ReadOnlyCollectionBase in the generics space.

Note, similarly, that IList<T> does not implement IList.

In general, pre-generics classes do not serve as useful abstractions for generic classes (with the exception of IEnumerable).


If you look at the history of the .net framework, you'll find generics since 2.0, but ReadOnlyCollectionBase already in 1.1. The reason for not choosing ReadOnlyCollectionBase is simple - it isn't generic, while the aim of ReadOnlyCollection<T> is to be generic. Thus it needs a much different inheritance tree.

The purpose for all the *CollectionBase classes was to provide a foundation for implementing strongly typed collections in .net 1.1. With the introduction of generics in 2.0, they became obsolete, however are still in the framework for backward compatibility.


If they did it would probably be a violation of Liskov's Substitution Principle.


Inheriting from a non-generic base class would be ineffecient. If the type was using a non-generic base, all it would be would be a thin layer above the base collection, where the generic features would simply derive from casting from the underlying object instances of the base collection.

This causes unnecessary boxing/unboxing of value types. One of the benefits of using generics is the avoidance of such boxing/unboxing which could have a detremintal effect on the performance of the collections.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜