可能重复:
C# - List <T>或IList <T>
我上课了
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我需要定义一个列表,并以下面的方式定义它之间的区别
IList<Employee> EmpList ;
Or
List<Employee> EmpList ;
Run Code Online (Sandbox Code Playgroud)
IList<>是一个界面.List<>是一个具体的课程.
任何这些都是有效的:
IList<Employee> EmpList = new List<Employee>();
Run Code Online (Sandbox Code Playgroud)
和
List<Employee> EmpList = new List<Employee>();
Run Code Online (Sandbox Code Playgroud)
要么
var EmpList = new List<Employee>(); // EmpList is List<Employee>
Run Code Online (Sandbox Code Playgroud)
但是,您无法实例化接口,即以下内容将失败:
IList<Employee> EmpList = new IList<Employee>();
Run Code Online (Sandbox Code Playgroud)
通常,使用依赖项(例如集合)的类和函数应该指定可能的限制性最小的接口(即最常用的接口).例如,如果您的方法只需要迭代一个集合,那么IEnumerable<>就足够了:
public void IterateEmployees(IEnumerable<Employee> employees)
{
foreach(var employee in employees)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
然而,如果消费者需要访问该Count属性(而不是必须通过迭代集合Count()),那么一个ICollection<T>或更好的,IReadOnlyCollection<T>将更合适,并且类似地,IList<T>仅在需要通过[]或表达该集合的随机访问时才需要需要在集合中添加或删除新项目.
IList<T> 是由实现的接口 List<T>.
您无法创建接口的具体实例,因此:
//this will not compile
IList<Employee> EmpList = new IList<Employee>();
//this is what you're really looking for:
List<Employee> EmpList = new List<Employee>();
//but this will also compile:
IList<Employee> EmpList = new List<Employee>();
Run Code Online (Sandbox Code Playgroud)
这里有两个答案.要存储实际列表,请使用a,List<T>因为您需要具体的数据结构.但是,如果您从属性返回它或将其作为参数,请考虑a IList<T>.它更通用,允许为参数传递更多类型.同样,它允许返回更多类型,而不仅仅是List<T>内部实现更改的情况.实际上,您可能希望考虑使用IEnumerable<T>返回类型.