IList<T>和List<T>的区别

9
可能重复:

可能重复:
C# - List<T> or IList<T>

我有一个类

 public class Employee
 {
      public int Id { get; set; }
      public string Name { get; set; }
 }

我需要定义一个列表,以下两种方式的区别是什么?
IList<Employee> EmpList ;

Or

List<Employee> EmpList ;
9个回答

14

IList<> 是一个 接口List<> 是一个具体类。

这些都是有效的:

 IList<Employee> EmpList = new List<Employee>();

并且

 List<Employee> EmpList = new List<Employee>();

或者

 var EmpList = new List<Employee>(); // EmpList is List<Employee>

然而,你不能实例化一个接口,也就是以下操作将失败:

IList<Employee> EmpList = new IList<Employee>();

通常,使用依赖项(如集合)的类和方法应指定最不限制的界面(即最通用的界面)。例如,如果您的方法只需要迭代一个集合,则 IEnumerable<> 就足够了:

public void IterateEmployees(IEnumerable<Employee> employees)
{
   foreach(var employee in employees)
   {
     // ...
   }
}

如果消费者需要访问“Count”属性(而不是通过“Count()”迭代集合),那么“ICollection”或更好的“IReadOnlyCollection”将更合适。同样地,只有在需要通过“[]”随机访问集合或表达新项需要添加或从集合中删除时才需要“IList”。请注意保留HTML标签。

7

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>();

2
是的,我同意,但我想知道根据什么情况我们需要决定使用哪个:List<Employee> EmpList = new List<Employee>();IList<Employee> EmpList = new List<Employee>(); - Coder

6

这里有两个答案。如果要存储实际列表,请使用 List<T>,因为需要具体的数据结构。但是,如果您从属性返回它或需要它作为参数,请考虑使用 IList<T>。它更通用,允许传递更多类型的参数。同样,在内部实现更改时,它允许返回比仅 List<T> 更多类型的内容。事实上,您可能要考虑将 IEnumerable<T> 用作返回类型。


我们什么时候需要使用IList和List?我知道IList是一个接口,而List继承了这个接口。请看下面的例子 - public class Test - Coder
1
@user1521931 这是一个设计问题。一般来说,我建议在字段中使用List<T>,而在属性和参数中使用IList<T> - akton

2

我会让您列举出不同之处,也许还可以添加一些巧妙的反思,但是一个List<T>实现了几个接口,而IList<T>只是其中之一:

[SerializableAttribute]
public class List<T> : IList<T>, ICollection<T>, 
    IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, 
    IEnumerable

2
List对象允许您创建一个列表,向其中添加内容,删除它,更新它,索引它等等。每当您只想要一个指定对象类型的通用列表时,就会使用List

IList则是一种接口。(有关接口的更多信息,请参见MSDN Interfaces)。基本上,如果你想创建自己的类型List,比如说一个叫做SimpleList的列表类,那么你可以使用接口为你的新类提供基本方法和结构。IList就是在你想创建实现List的特殊子类时所使用的接口。 您可以在这里看到示例


1

有许多类型的列表。它们中的每一个都继承自IList(这就是为什么它是一个接口)。两个例子是List(常规列表)和PagedList(这是一个具有分页支持的列表 - 它通常用于分页搜索结果)。PagedList和List都是ILists的类型,这意味着IList不一定是List(它可以是PagedList),反之亦然。

请参阅此链接上的PagedList。 https://github.com/TroyGoode/PagedList#readme


0

IList 是一个接口,List 是实现它的类,List 类型显式地实现了非泛型 IList 接口。


0

第一个版本是基于接口编程的,如果你只需要使用 IList 定义的方法,则更为推荐。第二个版本基于特定类的声明过于死板。


0

区别在于IList是一个接口,而List是一个类。 List实现了IList,但是无法实例化IList。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接