可能是重复问题:
为什么(真的吗?)List实现了这些接口而不仅仅是IList?
出于好奇,为什么泛型List<>实现非泛型接口IList?
示例代码
IList<int> list = new List<int>();
list.Add(1);
//compiles but ArgumentException thrown at run time
((IList)list).Add(new object());
可能是重复问题:
为什么(真的吗?)List实现了这些接口而不仅仅是IList?
出于好奇,为什么泛型List<>实现非泛型接口IList?
示例代码
IList<int> list = new List<int>();
list.Add(1);
//compiles but ArgumentException thrown at run time
((IList)list).Add(new object());
public SomeType this[int index] {get;}
SomeType
,那么List
就非常适合。因此,这提供了与现有代码的充分向后兼容性和通过此项支持的数据绑定。向后兼容。这样可以将其注入到旧的框架/库中,这些框架/库是1.0/1.1版本,或者是从1.0/1.1迁移过来但未完全重构,或者与2.0+ .Net框架中仍具有1.0/1.1接口的对象一起使用,而不必在新代码中放弃类型安全性。
ICollection<T>
包括 ICollection
,那么就会要求泛型集合实现非泛型接口。这种要求是不必要和繁琐的。这与原问题不同。IList<T>
也不包括 IList
。 - Jeffrey L Whitledge我相信List实现了IList的一个版本,因为这很容易做到,并且可能很有用,因为您不需要将列表包装在另一个类中才能传递它。
但是,它确实对您尝试添加的任何项进行类型检查,如果它们不匹配,则会抛出异常。
这样做的原因是让您能够拥有不同类型的ILists列表。
例如 -
List<int> ints = new List<int>();
List<string> strings = new List<string>();
List<IList> lists = new List<IList> { ints, strings};
IList.ReadOnly
返回与IList<T>.ReadOnly
不同的值,List<T>
可以以类型安全的方式实现IList<T>
。换句话说,我们可以使可变的List<T>
表现为类型安全的只读IList
。 - supercat