IList和IList <T>之间有什么区别

use*_*859 4 .net c# generics collections

List<T>in .net的定义表明它实现了各种接口.

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
Run Code Online (Sandbox Code Playgroud)

什么改变接口有没有T引入,IList即如果我的一个类实现IList<T>而不是IList,那么我可以使用它作为我的自定义集合类吗?

Ika*_*aso 11

,之所以List<T>同时实现了IList<T>IList是使其可用任何地方你的代码是假设的IList.这将使更容易转换到泛型,IList<T>因为它更合适.此外,如果您希望重用.net 1.1或更早版本的代码,即使您的类是在.net 2.0或更高版本的程序集中实现的,它也可以实现.


Mat*_*son 5

在a中,IList<T>您只能将定义的(T)类型的对象放入,IList可以包含不同类型的对象

由于AdressInformation不是客户列表中的有效对象,因此下面的代码将无法编译

IList<Customer> customers = new List<Customer>();
customers.Add(new Customer());
customers.Add(new AdressInformation());
Run Code Online (Sandbox Code Playgroud)

此代码将编译但在运行时转换异常

IList customers = new List<Customer>();
customers.Add(new Customer());
customers.Add(new AdressInformation());
Run Code Online (Sandbox Code Playgroud)

  • 当然它在运行时失败了...这就是泛型的全部意义!为什么它不应该失败 - 你将列表限制为只保存Customer实例,所以如果你突然被允许添加字符串,世界上就没有真相了. (3认同)
  • `IList`只是一个接口,而不是基类实现.它唯一强制的是该类实现了该公共接口.`List <T>`确实实现了该接口,因此它可以转换为`IList`.仅仅因为它的特定实现接口在使用无效参数调用时抛出异常并不意味着它不实现接口.接口不指定实现它的类何时可以抛出异常. (2认同)