为什么IEnumerator即使不可达,也必须至少具有一个yield语句? [英] Why does an IEnumerator have to have at least one yield statement, even if it's unreachable?

查看:91
本文介绍了为什么IEnumerator即使不可达,也必须至少具有一个yield语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要这段代码:

public IEnumerator Test()
{
}

给您一个错误:

错误CS0161'Test.GetEnumerator()':并非所有代码路径都返回一个值

Error CS0161 'Test.GetEnumerator()': not all code paths return a value

但是此代码:

public IEnumerator Test()
{
    if(false)
        yield return 0;
}

不是吗? (并按预期工作;首先MoveNext()返回false)

Doesn't? (and works as expected; first MoveNext() returns false)

当使用IEnumerators作为协程时,有时您想制作一个尚没有异步操作(不产生任何东西)但将来可能会做的协程(IEnumerator).

When using IEnumerators as coroutines, sometimes you want to make a coroutine (IEnumerator) that doesn't have an async operations yet (is not yielding anything) but might do that in future.

推荐答案

根据C#规范:

包含一个或多个yield语句(第8.14节)的块被称为 迭代器块.迭代器块用于实现功能 成员作为迭代器(第10.14节).

A block that contains one or more yield statements (§8.14) is called an iterator block. Iterator blocks are used to implement function members as iterators (§10.14).

因此,如果您有一个或多个yield语句,则无论是否可达,您的方法都是迭代器(在生成迭代器类的后台).但是,如果没有任何yield语句,则您的方法是序号方法(而不是迭代器),其返回值为IEnumerable类型.与其他任何返回某个值的方法一样,您必须返回所需类型的值或从方法主体中引发异常.当您具有返回stringint值的方法时,将应用相同的规则.

So if you have one or more yield statements, no matter reachable or not, your method is iterator (under the hood that will generate iterator class). But if you don't have any yield statements your method is the ordinal method (not an iterator) which has a return value of IEnumerable type. As any other method which returns some value, you must either return value of required type or throw an exception from method body. Same rules are applied when you have method which returns string or int value.

这篇关于为什么IEnumerator即使不可达,也必须至少具有一个yield语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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