enumerator如何不跳转而获取下一个对象
时间: 2024-01-25 20:02:18 浏览: 27
在 C# 中,可以使用 `yield return` 和 `yield break` 关键字来实现迭代器(iterator)的功能,从而不跳转而获取下一个对象。在迭代器中,使用 `yield return` 返回一个对象,并且暂停迭代器的执行,等待下一次迭代器调用时继续执行。而 `yield break` 则表示迭代器已经结束,不再返回任何对象。
对于 `enumerator` 来说,也可以使用迭代器来实现不跳转而获取下一个对象的功能。具体实现方式可以参考以下代码:
```
public class MyEnumerator<T> : IEnumerator<T>
{
private List<T> list;
private int index;
public MyEnumerator(List<T> list)
{
this.list = list;
this.index = -1;
}
public bool MoveNext()
{
if (index < list.Count - 1)
{
index++;
return true;
}
else
{
return false;
}
}
public void Reset()
{
index = -1;
}
public T Current
{
get
{
return list[index];
}
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose() { }
}
```
在这个例子中,`MyEnumerator` 类实现了 `IEnumerator` 接口,其中 `MoveNext` 方法使用了 `yield return` 关键字来实现不跳转而获取下一个对象的功能。我们可以使用以下代码来测试 `MyEnumerator` 类:
```
List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
MyEnumerator<int> enumerator = new MyEnumerator<int>(list);
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
```
输出结果为:
```
1
2
3
4
5
```
可以看到,使用迭代器实现的 `enumerator` 可以实现不跳转而获取下一个对象的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)