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

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

问题描述

我的问题不是如何解决这个错误(我已经解决了它),但是为什么这个错误与布尔值。

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。布尔只能取真或假。因此,将填充 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?

另外走了这个错误,如果伴随着真假情况下,我加入默认的情况下,却依然什么都一个布尔值从真假分开举行?

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?

推荐答案

你得到的错误是关于字符串变量和不可以 布尔可能值。

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

的事实,那就是没办法的的情况运行,没有人是真正的(在这种情况下),但是编译器不在分析code走这么远。它只是看起来对未分配,在某些条件下使用并没有默认的变量,因此假设还有的可以的一些情况时,它仍然未分配的。

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天全站免登陆