【问题标题】:Can I tell the outer function to return, from inside its local function?我可以告诉外部函数从其本地函数内部返回吗?
【发布时间】:2020-04-11 15:26:45
【问题描述】:

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

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

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()
    }
}

【问题讨论】:

    标签: c# local-functions


    【解决方案1】:

    您需要在 OuterFunction() 中放置 yield break。见What does "yield break;" do in 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()
    }
    }
    

    【讨论】:

    • 是的,我意识到这是一种可能性,但如上所述,不是 DRY 解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2011-01-08
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2015-06-01
    相关资源
    最近更新 更多