简体   繁体   English

C# 从 IF 语句中获取结果

[英]C# get Result from IF Statement

I have a simple code like:我有一个简单的代码,如:

public IActionResult TestingSample(int A, int B)
    {
        if (A > B && B != 0)
        {
            int corr = 2 + A * B;
            string rescorr = corr.ToString();
        }
        else
        {
            int wron = 2 * A + B;
            string reswron = wron.ToString();
        }
    }

From the code above, I want to add a result with: rescorr + reswron .从上面的代码中,我想添加一个结果: rescorr + reswron So it becomes string result.所以它变成了字符串结果。 How can I write the return value with string like that?我怎样才能用这样的字符串写返回值?

Really appreciated.非常感谢。
Thank you.谢谢你。

You should probably start by moving your string variables out of the if blocks您应该首先将字符串变量移出 if 块

And then return the concatenated string.然后返回连接的字符串。

public IActionResult TestingSample(int A, int B)
{
    string rescorr = string.Empty;
    string reswron = string.Empty;

    if (A > B && B != 0)
    {
        int corr = 2 + A * B;
        rescorr = corr.ToString();
    }
    else
    {
        int wron = 2 * A + B;
        reswron = wron.ToString();
    }

    return rescorr + reswron;
}

Then you realise that only 1 of these will ever get set so we change the string assignments in to individual returns.然后您意识到其中只有 1 个会被设置,因此我们将字符串分配更改为单独的返回值。 We get get rid of the variables and the else block because that's now redundant too.我们摆脱了变量和 else 块,因为它们现在也是多余的。

public IActionResult TestingSample(int A, int B)
{
    if (A > B && B != 0)
    {
        int corr = 2 + A * B;
        return corr.ToString();
    }

    int wron = 2 * A + B;
    return wron.ToString();

}

Something like this:像这样的东西:

 public IActionResult TestingSample(int A, int B) => A > B && B != 0 
     ? $"{2 + (long)A * B}"   // "correct"
     : $"{2L * A + B}";       // "wrong" 

here if A > B && B != 0 we have correct arguments and we return 2 + A * B , othevise arguments are wrong and we return 2 + A * B .这里如果A > B && B != 0我们有正确的参数,我们返回2 + A * B ,其他参数是错误的,我们返回2 + A * B

I've introduced long to fight with possible integer overflow (when, say, A == 2_000_000 , A = 1_000_000 )我已经引入了long来解决可能的整数溢出(例如,当A == 2_000_000 A = 1_000_000 , A = 1_000_000

Why don't you have a single string result?为什么没有单个字符串结果? if else will only return one如果否则只会返回一个

        string result = string.Empty;
        if (A > B && B != 0)
        {
            int cal = 2 + A * B;
            result = cal.ToString();
            return result;
        }
                
        int cal = 2 * A + B;
        result = cal.ToString();
        return result;
        

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

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