gpt4 book ai didi

c# - 为什么 IEnumerable 继承自 IEnumerable?

转载 作者:IT王子 更新时间:2023-10-29 04:04:31 26 4
gpt4 key购买 nike

这可能是一个老问题:为什么 IEnumerable<T>继承自 IEnumerable

.NET就是这样做的,但是带来了一点麻烦。每次我写一个类实现IEumerable<T> , 我必须写两个 GetEnumerator()函数,一个用于 IEnumerable<T>另一个是IEnumerable .

并且,IList<T>不继承自 IList。

不知道为什么IEnumerable<T>以其他方式设计。

最佳答案

Straight from the horse's mouth (海尔斯堡):

Ideally all of the generic collection interfaces (e.g. ICollection<T>, IList<T>) would inherit from their non-generic counterparts such that generic interface instances could be used both with generic and non-generic code. For example, it would be convenient if an IList<T> could be passed to code that expects an IList.

As it turns out, the only generic interface for which this is possible is IEnumerable<T>, because only IEnumerable<T> is contra-variant: In IEnumerable<T>, the type parameter T is used only in "output" positions (return values) and not in "input" positions (parameters). ICollection<T> and IList<T> use T in both input and output positions, and those interfaces are therefore invariant. (As an aside, they would have been contra-variant if T was used only in input positions, but that doesn't really matter here.)

<...snip...>

所以,为了回答您的问题,IEnumerable<T>继承自 IEnumerable因为它可以! :-)

关于c# - 为什么 IEnumerable<T> 继承自 IEnumerable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/221691/

26 4 0