如何将多个bool声明为false

时间:2017-08-31 08:14:05

标签: c# .net

而不是声明:

bool one = false;
bool two = false;
bool three = false;

是否可以声明如下内容:

bool one, two, three;

将所有内容设置为false

bool one, two, three = false

8 个答案:

答案 0 :(得分:6)

  

bool变量的默认值为false。 bool的默认值?变量为空。

供参考,您可以访问:bool (C# Reference).

但除非assigned包含值,否则无法使用它。

bool one, two, three;
one = two = three = false

与可以为空的布尔值相同:

bool? isCase = null;
if (isCase.HasValue){
    //TODO:
   }

答案 1 :(得分:4)

你可以这样做:

bool one = false, two = false, three = false

或者

bool one, two, three;
one = two = three = false;

答案 2 :(得分:3)

默认情况下,bools为false。

所以

bool one, two, three;

给你三个bool设置为false。但是 - 当你尝试使用它们时,你会收到错误,例如:

  

使用未分配的本地变量'三'

您需要在使用它们之前初始化它们:

bool one = false, two = false,three = false;

答案 3 :(得分:2)

没有内置语法可以做到这一点。虽然bool的默认值为false,但C#要求您在使用它们之前初始化变量。

我无法想到的唯一方法可能是帮助你声明一个数组:

bool[] bools = new bool[3];
Console.WriteLine(bools[0]);
Console.WriteLine(bools[1]);
Console.WriteLine(bools[2]);

数组初始化为false个值,但是你松开了变量名的语义(所以我实际上更喜欢Ashkan的答案)。

答案 4 :(得分:1)

2更短的方法是:

bool one = false, two = false, three = false;

或者:

bool one, two, three;
one = two = three = false;

答案 5 :(得分:0)

这样:

bool one, two;
one = two = true;

答案 6 :(得分:0)

简单地说,就像这样:

one = two = three = false

答案 7 :(得分:0)

如果它们太多则将它们放入数组并使用循环。 否则,我认为这很好。

bool one, two, three;
one = two = three = false;
相关问题