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或更高版本的程序集中实现的,它也可以实现.
在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)