文章不定时更新,有问题的话欢迎各位dalao指正。
枚举器和迭代器
枚举器与可枚举类型
foreach:
我们可以通过foreach来便历或取出数组中的每一个元素:
int[] arr1 = {
10, 11, 12, 13 };
foreach(int item in arr1)
{
Console.WriteLine($"value:{
item}");
}
输出:
value:10
value:11
value:12
value:13
foreach中in后面跟的参数必须是可枚举类型(enumerable type)。
可枚举类型是实现了GetEnumerator方法的类型,而GetEnumerator方法是获取对象枚举器的方法,对于枚举器而言,必须有个方法去获取他。
IEnumerator和IEnumerable
1、IEnumerator
namespace System.Collections
{
//
// 摘要:
// Supports a simple iteration over a non-generic collection.
public interface IEnumerator
{
//
// 摘要:
// Gets the element in the collection at the current position of the enumerator.
//
// 返回结果:
// The element in the collection at the current position of the enumerator.
object? Current {
get; }
//
// 摘要:
// Advances the enumerator to the next element of the collection.
//
// 返回结果:
// true if the enumerator was successfully advanced to the next element; false if
// the enumerator has passed the end of the collection.
//
// 异常:
// T:System.InvalidOperationException:
// The collection was modified after the enumerator was created.
bool MoveNext();
//
// 摘要:
// Sets the enumerator to its initial position, which is before the first element
// in the collection.
//
// 异常:
// T:System.InvalidOperationException:
// The collection was modified after the enumerator was created.
void Reset();
}
}
Current、MoveNext()、Reset是枚举器的三个成员
Current只读,获取集合中枚举器当前位置的元素
MoveNext()将枚举器前进到集合的下一个元素。
Reset()将枚举数设置为其初始位置,即集合中第一个元素之前的位置(-1)。
其实在我们使用foreach语句的时候,C#编译器会生成和下面非常相似的代码。
int[] arr1 = {
10, 11, 12, 13 };
IEnumerator ie = arr1.GetEnumerator();
while (ie.MoveNext())//移到下一项
{
int i = (int)ie.Current;//获取当前项
Console.WriteLine($"{
i}");
}
10
11
12
13
2、IEnumerable
实现了IEnumerable接口的类叫做可枚举类。
IEnumerable接口中的GetEnumerator 方法返回对象的枚举器。
声明:
class MyClass : IEnumerable//实现IEnumerable接口
{
public IEnumerator GetEnumerator() {
//函数返回IEnumerator类型的对象
}
}
使用IEnumerator和IEnumerable的示例:
class ColorEnumerator

最低0.47元/天 解锁文章
801

被折叠的 条评论
为什么被折叠?



