gpt4 book ai didi

c# - 为什么泛型 IList<> 不继承非泛型 IList

转载 作者:可可西里 更新时间:2023-11-01 07:57:28 30 4
gpt4 key购买 nike

IList<T>不继承 IList其中 IEnumerable<out T>继承IEnumerable .

如果out修饰符是大多数执行 IList<T> 的唯一原因(例如 Collection<T>List<T> )实现 IList界面。

所以任何人都可以说 OK,如果该陈述对于 IList<T> 的所有实现都是正确的然后直接投给IList必要时。但问题是虽然 IList<T>不继承IList所以不能保证每个IList<T>对象是 IList .

此外使用 IList<object>显然不是解决方案,因为没有 out不能将修饰泛型分配给较少继承的类;并且创建新的 List 实例不是这里的解决方案,因为有人可能想要实际引用 IList<T>作为IList指针;并使用 List<T>代替IList<T>实际上是一种糟糕的编程习惯,并不能达到所有目的。

如果 .NET 想要为 IList<T> 的每个实现提供灵 active 不应该有非泛型实现的契约(即 IList )那么为什么他们不保留另一个实现泛型和非泛型版本的接口(interface)并且不建议所有想要为泛型和非泛型契约的具体类非基因元素应通过该接口(interface)收缩。

类型转换时出现同样的问题ICollection<T>ICollectionIDictionary<TKey, TValue>IDictionary .

最佳答案

如您所见,TIList<T>不是协变的。根据经验:任何可以修改其状态的类都不能是协变的。原因是此类类通常具有具有 T 的方法。作为其参数之一的类型,例如void Add(T element) .并且输入位置不允许协变类型参数。

除其他原因外,添加泛型是为了提供类型安全。例如,您不能添加 ElephantApple 的列表.如果ICollection<T>将延长 ICollection , 然后你可以打电话 ((ICollection)myApples).Add(someElephant)没有编译时错误,如 ICollection有一个方法 void Add(object obj) ,这似乎允许您将任何对象添加到列表中,而实际上您只能添加 T 的对象。 .因此,ICollection<T>不扩展 ICollectionIList<T>不扩展 IList .

Anders Hejlsberg,C# 的创建者之一,explains it like this :

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.

As it turns out, the only generic interface for which this is possible is IEnumerable<T>, because only IEnumerable<T> is contra-variant [sic1]: 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.

1) IEnumerable<T>-变体


从 .Net 4.5 开始有 IReadOnlyCollection<out T> IReadOnlyList<out T> 协变接口(interface)。但是IList<T> , ICollection<T>许多列表和集合类没有实现或扩展它们。坦率地说,我发现它们不是很有用,因为它们只定义了 Count。和 this[int index] .


如果我可以从头开始重新设计 .Net 4.5,我会将列表接口(interface)拆分为只读协变接口(interface) IList<out T>其中包括 ContainsIndexOf , 和一个可变的不变接口(interface) IMutableList<T> .然后你可以投 IList<Apple>IList<object> .我在这里实现了这个:

M42 Collections - Covariant collections, lists and arrays.

关于c# - 为什么泛型 IList<> 不继承非泛型 IList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14559070/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com