有人能给我解释一下IEnumerable和IEnumerator吗?
例如,什么时候用它胜过foreach?IEnumerable和IEnumerator的区别是什么?为什么我们需要使用它?
有人能给我解释一下IEnumerable和IEnumerator吗?
例如,什么时候用它胜过foreach?IEnumerable和IEnumerator的区别是什么?为什么我们需要使用它?
当前回答
IEnumerable和IEnumerator都是c#中的接口。
IEnumerable是一个接口,它定义了一个返回IEnumerator接口的方法GetEnumerator()。
这适用于对集合的只读访问,该集合实现了IEnumerable可与foreach语句一起使用。
IEnumerator有两个方法,MoveNext和Reset。它还有一个名为Current的属性。
下面展示了IEnumerable和IEnumerator的实现。
其他回答
例如,什么时候用它胜过foreach?
你不用IEnumerable "over" foreach。实现IEnumerable使得使用foreach成为可能。
当你写这样的代码时:
foreach (Foo bar in baz)
{
...
}
它在功能上相当于这样写:
IEnumerator bat = baz.GetEnumerator();
while (bat.MoveNext())
{
bar = (Foo)bat.Current
...
}
所谓“功能等效”,我指的是编译器实际将代码转换成的内容。在本例中,除非baz实现了IEnumerable,否则不能在baz上使用foreach。
IEnumerable表示baz实现了该方法
IEnumerator GetEnumerator()
该方法返回的IEnumerator对象必须实现这些方法
bool MoveNext()
and
Object Current()
第一个方法前进到创建枚举器的IEnumerable对象中的下一个对象,如果完成则返回false,第二个方法返回当前对象。
. net中任何你可以迭代的东西都实现了IEnumerable。如果您正在构建自己的类,并且它还没有从实现了IEnumerable的类继承,那么您可以通过实现IEnumerable(并通过创建其新的GetEnumerator方法将返回的枚举器类)使您的类在foreach语句中可用。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Enudemo
{
class Person
{
string name = "";
int roll;
public Person(string name, int roll)
{
this.name = name;
this.roll = roll;
}
public override string ToString()
{
return string.Format("Name : " + name + "\t Roll : " + roll);
}
}
class Demo : IEnumerable
{
ArrayList list1 = new ArrayList();
public Demo()
{
list1.Add(new Person("Shahriar", 332));
list1.Add(new Person("Sujon", 333));
list1.Add(new Person("Sumona", 334));
list1.Add(new Person("Shakil", 335));
list1.Add(new Person("Shruti", 336));
}
IEnumerator IEnumerable.GetEnumerator()
{
return list1.GetEnumerator();
}
}
class Program
{
static void Main(string[] args)
{
Demo d = new Demo(); // Notice here. it is simple object but for
//IEnumerator you can get the collection data
foreach (Person X in d)
{
Console.WriteLine(X);
}
Console.ReadKey();
}
}
}
/*
Output :
Name : Shahriar Roll : 332
Name : Sujon Roll : 333
Name : Sumona Roll : 334
Name : Shakil Roll : 335
Name : Shruti Roll : 336
*/
实现IEnumerable意味着你的类返回一个IEnumerator对象:
public class People : IEnumerable
{
IEnumerator IEnumerable.GetEnumerator()
{
// return a PeopleEnumerator
}
}
实现IEnumerator意味着你的类返回迭代的方法和属性:
public class PeopleEnumerator : IEnumerator
{
public void Reset()...
public bool MoveNext()...
public object Current...
}
这就是区别所在。
IEnumerable和IEnumerator都是c#中的接口。
IEnumerable是一个接口,它定义了一个返回IEnumerator接口的方法GetEnumerator()。
这适用于对集合的只读访问,该集合实现了IEnumerable可与foreach语句一起使用。
IEnumerator有两个方法,MoveNext和Reset。它还有一个名为Current的属性。
下面展示了IEnumerable和IEnumerator的实现。
我注意到了这些不同之处:
A.我们以不同的方式迭代列表,foreach可用于IEnumerable, while loop可用于IEnumerator。
B.当我们从一个方法传递到另一个方法时,IEnumerator可以记住当前索引(它开始使用当前索引),但IEnumerable不能记住索引,它将索引重置为开始。更多内容请参见https://www.youtube.com/watch?v=jd3yUjGc9M0