1

我有一个 IEnumerator,我需要在函数内部进行一些检查,如果其中一些检查失败,我需要进行一些维护,然后退出 IEnumerator。但是当我写入yield break内部函数时,它认为我正在尝试从该内部函数返回。

我想我可以yield break在内部函数调用之后写,但我想保持干燥。

private IEnumerator OuterFunction()
{
    //bla bla some code

    //some check:
    if (!conditionA)
        Fail();

    //if didn't fail, continue normal code

    //another check:
    if (!conditionB)
        Fail();

    //etc....

    //and here's the local function:
    void Fail()
    {
        //some maintenance stuff I need to do

        //and after the maintenance, exit out of the IEnumerator:
        yield break;
        //^ I want to exit out of the outer function on this line
        //but the compiler thinks I'm (incorrectly) returning from the inner function Fail()
    }
}
4

1 回答 1

0

您需要在 OuterFunction() 中放置 yield break。请参阅什么是“收益率中断”;在 C# 中做?

private IEnumerator OuterFunction()
{
    //bla bla some code

//some check:
if (!conditionA){
    Fail();
    yield break;
}

//if didn't fail, continue normal code

//another check:
if (!conditionB){
    Fail();
    yield break;
}

//etc....

//and here's the local function:
void Fail()
{
    //some maintenance stuff I need to do

    //and after the maintenance, exit out of the IEnumerator:

    //^ I want to exit out of the outer function on this line
    //but the compiler thinks I'm (incorrectly) returning from the inner function Fail()
}
}
于 2019-12-19T05:21:17.203 回答