Joe*_*orn 67
这是......你可以循环的东西...... 这可能是List或Array或(几乎)支持foreach循环的任何其他内容.它适用于您希望能够使用带foreach循环的对象,但您不知道您正在处理的确切类型,无论是Array,List还是自定义的东西.
所以这是第一个优点:如果你的方法接受IEnumerable而不是数组或列表,它们会变得更强大,因为你可以向它们传递更多不同类型的对象.
现在使IEnumerable真正脱颖而出的是迭代器块(yieldC#中的关键字).Iterator块像List或Array一样实现IEnumerable接口,但它们非常特殊,因为与List或Array不同,它们通常一次只保持单个项的状态.因此,例如,如果要在非常大的文件中循环遍历行,则可以编写迭代器块来处理文件输入.那么你一次在内存中永远不会有多行文件,如果你之前完成了循环(也许是搜索,你找到了你需要的东西),你可能不需要读取整个文件.或者,如果您正在从大型SQL查询中读取结果,则可以将内存使用限制为单个记录.
另一个特点是这个评估是懒惰的,所以如果你正在做复杂的工作来评估可枚举的内容,那么这项工作要么在被要求之后才会发生.这是非常有益的,因为经常(例如,再次搜索)你会发现你可能根本不需要做任何工作.
您可以将IEnumerable视为即时列表.
Jus*_*ner 34
它是由.NET中的Collection类型实现的接口,提供Iterator模式.还有通用版本IEnumerable<T>.
通过实现IEnumerable的集合移动的语法(你很少看到因为有更漂亮的方法):
IEnumerator enumerator = collection.GetEnumerator();
while(enumerator.MoveNext())
{
object obj = enumerator.Current;
// work with the object
}
Run Code Online (Sandbox Code Playgroud)
功能相当于:
foreach(object obj in collection)
{
// work with the object
}
Run Code Online (Sandbox Code Playgroud)
如果集合支持索引器,您也可以使用经典的for循环方法对其进行迭代,但Iterator模式提供了一些很好的附加功能,例如为线程添加同步的功能.
Dav*_*rab 12
首先它是一个界面.根据MSDN的定义是
公开枚举器,它支持对非泛型集合的简单迭代.
以一种非常简单的方式说,实现此接口的任何对象都将提供获取枚举器的方法.枚举器与foreach一个例子一起使用.
List实现IEnumerable接口.
// This is a collection that eventually we will use an Enumertor to loop through
// rather than a typical index number if we used a for loop.
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
// HERE is where the Enumerator is gotten from the List<string> object
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
// You could do a
for(int i = 0; i < dinosaurs.Count; i++)
{
string dinosaur = dinosaurs[i];
Console.WriteLine(dinosaur);
}
Run Code Online (Sandbox Code Playgroud)
foreach看起来更干净.