具有布尔值的开关盒的奇怪行为 [英] Strange behaviour of switch case with boolean value

查看:17
本文介绍了具有布尔值的开关盒的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的功能是

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;
}

错误是使用未分配的局部变量'str'.Bool 只能取真或假.因此,无论哪种情况,它都会填充 str .那为什么会出现这个错误呢?

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

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

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

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

Why this strange behaviour with bool variable?

推荐答案

你得到的错误是关于 string 变量和 not boolean 可能的价值观.

The error you get is about string variable and not boolean possible values.

cases 中没有一个不可能运行的事实是正确的(在这种情况下),但编译器在分析代码.它只是查看在某些情况下未分配和使用的变量,并且没有默认变量,因此 假设 可能 在某些情况下它仍然未分配.

The fact that there is no way that noone of cases run, 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 suppose that there could be some case when it remains unassigned.

这篇关于具有布尔值的开关盒的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆