C# 带有布尔值的 switch case 的奇怪行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11097927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:28:25  来源:igfitidea点击:

Strange behaviour of switch case with boolean value

c#.netbooleanswitch-statement

提问by Nikhil Agrawal

My question is not about how to solve this error(I already solved it) but why is this error with boolean value.

我的问题不是关于如何解决这个错误(我已经解决了),而是为什么这个错误带有布尔值。

My function is

我的功能是

private string NumberToString(int number, bool flag)
{
    string str;

    switch(flag)
    {
        case true: 
            str = number.ToString("00");
            break;
        case false:
            str = number.ToString("0000"); 
            break;
    }

    return str;
}

Error is Use of unassigned local variable 'str'. Bool can only take true or false. So it will populate strin either case. Then why this error?

错误是Use of unassigned local variable 'str'。Bool 只能取真或假。所以它会str在任何一种情况下填充。那为什么会出现这个错误呢?

Moreover this error is gone if along with true and false case I add a defaultcase, but still what can a bool hold apart from true and false?

此外,如果与真假案例一起添加default案例,则此错误消失了,但是除了真假之外,布尔值还能保持什么?

Why this strange behaviour with bool variable?

为什么 bool 变量会出现这种奇怪的行为?

采纳答案by Tigran

The error you get is about stringvariable and notbooleanpossible values.

你得到的错误是关于string变量而不是boolean可能的值。

The fact that there is no waythat noone of casesrun, is a true (in this case), but compiler doesn't go so far in analyzing the code. It just looks on variable that is not assigned and used in some conditions and there is not default one, so supposethat there couldbe some case when it remains unassigned.

事实上,有没有办法说的没有人cases来看,是一个真正的(在这种情况下),但编译器不会在分析代码走这么远。它只是看起来不分配,并在某些情况下使用并没有默认的变量,所以可能时保持未分配的一些情况。

回答by levi

private string NumberToString(int number, bool flag)
{
    string str = "";

    switch(flag)
    {
        case true: 
            str = number.ToString("00");
            break;
        case false:
            str = number.ToString("0000"); 
            break;
    }

    return str;
}

write thisstring str = "";- you should assign value

写这个string str = "";- 你应该赋值

if you add default case there is no chance to fall through the switch cases without assigning. Now it is

如果您添加默认情况,则没有机会在没有分配的情况下通过 switch case。现在它是

回答by Habib

I think, you are trying to ask, why strvariable is unassigned, as the switch statement's cases will assign it some value, but the compiler can't determine whether it will fall in any of the case statement, That is why you are getting this error on returning str.

我想,你是想问,为什么str变量没有赋值,因为 switch 语句的 case 会为其分配一些值,但编译器无法确定它是否会落在任何 case 语句中,这就是为什么你得到这个返回时出错str

If you add a default case with string assignment, then the compiler will know for sure that, the str will hold some value and that is why you don't get error

如果你添加一个带有字符串赋值的默认情况,那么编译器肯定会知道,str 会保存一些值,这就是为什么你不会出错

回答by Darin Dimitrov

Writing a switch statement on a boolean variable seems kinda wasty to me. Why not use the conditional operator (?:):

在布尔变量上编写 switch 语句对我来说似乎有点浪费。为什么不使用条件运算符 ( ?:):

private string NumberToString(int number, bool flag)
{
    return flag ? number.ToString("00") : number.ToString("0000"); 
}

The code seems a bit more concise and you don't need local variables.

代码看起来更简洁一些,并且不需要局部变量。

But back to your question about why your code doesn't compile => it is because variables must always be assigned and this assignment should not happen inside conditional statements.

但是回到你关于为什么你的代码不能编译的问题 => 这是因为变量必须总是被分配并且这个分配不应该发生在条件语句中。

回答by Alex

Well, there's been good explanation for causes of this issue, but there is one more solution to the problem, which was not mentioned. Just put defaultinstead of second case:

好吧,对于这个问题的原因已经有了很好的解释,但是还有一个没有提到的问题的解决方案。只需放置default而不是第二个case

    private string NumberToString(int number, bool flag)
    {
        string str;

        switch (flag)
        {
            case true:
                str = number.ToString("00");
                break;
            default:
                str = number.ToString("0000");
                break;
        }

        return str;
    }

It leaves compiler with no further thoughts about flagvariable value as we always assign a defaultvalue in our switchstatement.

它让编译器不再考虑flag变量值,因为我们总是default在我们的switch语句中分配一个值。

Also consider if-else statement equivalent solution:

还要考虑 if-else 语句等效解决方案:

    private string NumberToString(int number, bool flag)
    {
        string str;

        if (flag)
            str = number.ToString("00");
        else
            str = number.ToString("0000");

        return str;
    }

I am not particularly fond of 'one-liners' (one line solutions), as they lack extendability and moreover - readability, but as the last resort just use ternary operators like this:

我不是特别喜欢“单行”(单行解决方案),因为它们缺乏可扩展性和可读性,但作为最后的手段,只使用这样的三元运算符:

    private string NumberToString(int number, bool flag)
    {
        return flag ? number.ToString("00") : number.ToString("0000");
    }

While I am at it - consider using extension method + defaulting boolean to false, for example:

当我在做的时候 - 考虑使用扩展方法 + 默认布尔值为false,例如:

public static class intExtensions
{
    public static string NumberToString(this int number, bool flag = false)
    {
        return flag ? number.ToString("00") : number.ToString("0000");
    }
}

and then in main class:

然后在主类中:

        int intVal = 56;
        string strVal1 = intVal.NumberToString(true);
        string strVal2 = intVal.NumberToString();