简体   繁体   English

C#中的一般多回报声明问题

[英]General Multi Return Statement Question in C#

How to return the value if I doesn't need hit block2. 如果我不需要命中block2,如何返回值。

Does it make sense or not? 它有意义吗? I think I shouldn't use multi return , but I can't replace it with break . 我想我不应该使用多return ,但我不能用break替换它。 there is No enclosing loop out of which to break or continue . 没有封闭的循环可以打破或继续

public EnResult MyFun()
{
    bool bRet = default;

    // block1 . higher priority than block2.
    if (true)
    {
    // if bRet = true_1, not need hit block2. That's why I want to nested my code with multi *return*
        return bRet = true_1;  
    }
    else
    {
        // do nothing
    }

    // block2
    if (true)
    {
        return bRet = true_2;
    }
    else
    {
        // do nothing
    }

    return bRet;
}

public enum EnResult
{
    true_1,
    true_2,
    false_1,
    false_2,
    default,
}

Using multiple return statements per method is not poor coding style at all. 每种方法使用多个return语句根本不是很差的编码风格。 Limiting yourself to one return statement makes sense in C, where you may need to goto some common cleanup code that will free pointers, etc., and then return the value you have stored in a variable. 将自己限制为一个return语句在C中是有意义的,您可能需要goto一些可以释放指针等的常用清理代码,然后返回存储在变量中的值。 But in C# this is not necessary. 但在C#中,这不是必需的。

I write methods with multiple return statements all the time. 我一直用多个return语句编写方法。 I would much rather read a method written with multiple return statements where the logic flow is clear, than read a method written with one return statement and somewhat obfuscated logic. 我更愿意阅读一个用多个return语句编写的方法,其中逻辑流是明确的,而不是读取一个用一个return语句编写的方法和一些模糊的逻辑。

If you don't want to use a "multi-return": 如果您不想使用“多次退货”:

public EnResult MyFun()
{
    // I changed 'default' to 'None' because I wasn't sure if it compiled
    EnResult result = EnResult.None;

    // block1 . higher priority than block2.
    if (true)
    {
        result = EnResult.true_1;
    }
    else
    {
        // do nothing
    }

    // block2
    if (result == EnResult.None)
    {
        if (true)
        {
            result = EnResult.true_2;
        }
        else
        {
            // do nothing
        }
    }

    return result;
}

public enum EnResult
{
    None,  
    true_1,
    true_2,
    false_1,
    false_2,

}

I would prefer using multiple return statements though (your original code). 我更喜欢使用多个return语句(您的原始代码)。 It's much more clear that way IMO. IMO的方式更加清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM