简体   繁体   English

为什么ICollection <T>实现IEnumerable <T>和IEnumerable

[英]Why does ICollection<T> implement both IEnumerable<T> and IEnumerable

Why does ICollection<T> implement both IEnumerable<T> and IEnumerable ? 为什么ICollection<T>实现IEnumerable<T>IEnumerable

What is the purpose of this? 这样做的目的是什么? How does IEnumerable benefit ICollection<T> ? IEnumerable如何使ICollection<T>受益?

IEnumerable<T> itself forces any implementation to also implement the non-generic IEnumerable . IEnumerable<T>本身强制任何实现也实现非通用的IEnumerable This is safe, for the same reasons that IEnumerable<out T> is covariant as of .NET 4... you can always convert the T to object for the non-generic form. 这是安全的,出于同样的原因, IEnumerable<out T>在.NET 4中是协变的......你总是可以将T转换为非泛型形式的object

Basically this means that if you've got code which uses a parameter of type IEnumerable , you can still call it with something like List<T> . 基本上这意味着如果你有使用IEnumerable类型参数的代码,你仍然可以用类似List<T>调用它。

Eric Lippert wrote a blog post recently about why collections end up implementing many interfaces, and Brad Abrams wrote a blog post back in 2005 about the specific IEnumerable<T> / IEnumerable decision. Eric Lippert 最近写了一篇关于为什么集合最终会实现许多接口的博客文章 ,而Brad Abrams 在2005年写了一篇关于特定IEnumerable<T> / IEnumerable决定的博客文章

The non-generic interface is for backward compatibility. 非通用接口用于向后兼容。 If you write code using generics and want to pass your collection to some module written in .NET 1.0 (which doesn't have generics) you still want this to succeed, and you want the old method to be able to iterate through it. 如果您使用泛型编写代码并希望将您的集合传递给用.NET 1.0编写的某个模块(没有泛型),您仍然希望这成功,并且您希望旧方法能够遍历它。

IEnumerable<T> inherits IEnumerable so it makes sense for ICollection<T> to as well. IEnumerable<T>继承了IEnumerable因此ICollection<T>也是有意义的。 It's just stating explicitly the inheritance that would be there anyway. 它只是明确说明了那里的继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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