IEnumerable和数组有什么区别?

Nis*_*mar 8 c# ienumerable

是否有人会描述IEnumerable以及IEnumerable和数组之间的区别以及在何处使用它...所有关于它的信息以及如何使用它.

Mar*_*ris 11

数组是具有设置大小的对象的集合.

int[] array = [0, 1, 2];
Run Code Online (Sandbox Code Playgroud)

这使得它在您可能想要访问集合中特定位置的项目时非常有用,因为每个元素的内存中的位置已知

array[1];
Run Code Online (Sandbox Code Playgroud)

此外,可以快速计算阵列的大小.

另一方面,IEnumerable基本上表示给定起始位置可以获得下一个值.这方面的一个例子可能是一系列无数的数字:

public IEnumerable<int> Infinite()
{
    int i = 0;
    while(true)
        yield return i++;
}
Run Code Online (Sandbox Code Playgroud)

与数组不同,可枚举集合可以是任何大小,并且可以在需要时创建元素,而不是在前面,这允许强大的构造,并且LINQ广泛使用它来促进复杂查询.

//This line won't do anything until you actually enumerate the created variable
IEnumerable<int> firstTenOddNumbers = Infinite().Where(x => x % 2 == 1).Take(10);
Run Code Online (Sandbox Code Playgroud)

但是,获取特定元素的唯一方法是从头开始并枚举到您想要的那个元素.这比从预生成的数组中获取元素要昂贵得多.

当然,您可以枚举数组,因此数组实现IEnumerable接口.

  • @djacobson它*是*无限的,它不是连续的.下一个值是-2147483648 ...... :) (7认同)
  • +1彻底回答......尽管2147483647几乎无穷无尽.;) (2认同)