返回一个空的IEnumerator [英] Return an empty IEnumerator

查看:63
本文介绍了返回一个空的IEnumerator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接口,除其他外,该接口实现了 public IEnumerator GetEnumerator()方法,因此我可以在foreach语句中使用该接口。

I have an interface that, among other things, implements a "public IEnumerator GetEnumerator()" method, so I can use the interface in a foreach statement.

我在几个类中实现了此接口,在其中一个类中,我想返回一个空的IEnumerator。现在,我按以下方式执行此操作:

I implement this interface in several classes and in one of them, I want to return an empty IEnumerator. Right now I do this the following way:

public IEnumerator GetEnumerator()
{
    ArrayList arr = new ArrayList();
    return arr.GetEnumerator();
}

但是我认为这很丑陋,我不禁要想有更好的方法返回空IEnumerator。

However I consider this an ugly hack, and I can't help but think that there is a better way of returning an empty IEnumerator. Is there?

推荐答案

这在C#2中很简单:

public IEnumerator GetEnumerator()
{
    yield break;
}

您需要收益减免强制编译器将其视为迭代器块。

You need the yield break statement to force the compiler to treat it as an iterator block.

这将比自定义空迭代器效率低,但它的代码更简单...

This will be less efficient than a "custom" empty iterator, but it's simpler code...

这篇关于返回一个空的IEnumerator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆