C# 中 IEnumerator 和 IEnumerable 接口的区别
csharpprogrammingserver side programming更新于 2025/11/24 2:18:00
IEnumerable 和 IEnumerator 都是 C# 中的接口。
IEnumerable 是一个接口,它定义了一个方法 GetEnumerator(),该方法返回一个 IEnumerator 接口。
这适用于对实现该 IEnumerable 的集合的只读访问,可以将其与 foreach 语句一起使用。
IEnumerator 有两种方法 MoveNext 和 Reset。它还有一个名为 Current 的属性。
以下显示了 IEnumerable 和 IEnumerator 的实现。
示例
class Demo : IEnumerable, IEnumerator {
// IEnumerable method GetEnumerator()
IEnumerator IEnumerable.GetEnumerator() {
throw new NotImplementedException();
}
public object Current {
get { throw new NotImplementedException(); }
}
// IEnumerator 方法
public bool MoveNext() {
throw new NotImplementedException();
}
// IEnumerator 方法
public void Reset() {
throw new NotImplementedException();
}
}
Above you can see the two methods of IEnumerator.
// IEnumerator 方法
public bool MoveNext() {
throw new NotImplementedException();
}
// IEnumerator 方法
public void Reset() {
throw new NotImplementedException();
}

