C# 检查可空布尔值是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13304676/
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-10 08:09:56  来源:igfitidea点击:

checking if a nullable bool is null or not

c#

提问by Amin Ziaei

Possible Duplicate:
Which is preferred: Nullable<>.HasValue or Nullable<> == null?

可能的重复:
哪个是首选:Nullable<>.HasValue 或 Nullable<> == null?

I know questions like this have been asked many times. But I never found an answer to how to check if a nullable bool is null or not. Here is an answer I have to this:

我知道这样的问题已经被问过很多次了。但我从未找到如何检查可空 bool 是否为空的答案。这是我对此的回答:

bool? nullableBool;
if (nullableBool == true){

}else if (nullableBool == false){

}else{

}

But I was wondering if there is a better and more straight to the point way in order to minimize useless codes? Thanks.

但我想知道是否有更好更直接的方式来减少无用代码?谢谢。

采纳答案by tukaef

if (!nullableBool.HasValue)
{
    // null
}

You also can directly compare it with null.

您也可以直接将其与null.

Edit:

编辑:

Your declaration of nullableBoolshould be:

您的声明nullableBool应该是:

bool? nullableBool;

回答by bonCodigo

Try this plz:

试试这个:

if (!nullableBool.HasValue)
{
    // your code
}

回答by Rawling

That's not a nullable bool, it's an unassigned booland your code won't compile. You need to use bool?or Nullable<bool>.

那不是可空的bool,它是未分配的bool,您的代码将无法编译。您需要使用bool?Nullable<bool>

bool? nullableBool = null; // or = true or = false
if (nullableBool.HasValue)
{
    if (nullableBool.Value)
        // true
    else
       // false
}
else
    // null

回答by musefan

Firstly, the bool you have used is not nullable. To create a nullable bool you can do one fo the following:

首先,您使用的 bool 不可为空。要创建可为空的 bool,您可以执行以下操作之一:

Nullable<bool> nullableBool;

or the shorthand version:

或速记版本:

bool? nullableBool;

either of these can then be checked to see if it has a value using the following:

然后可以使用以下方法检查它们中的任何一个以查看它是否具有值:

if(nullableBool.HasValue)
{
   //nullableBool has been assigned a value
}

Your current approach is not recommended. If you need a nullable state then use a nullable bool. If you want to use a standard bool then be sure to assign it a value. I am surprised you don't get a compile error in Visual Studio with that code.

不推荐您当前的方法。如果您需要可空状态,则使用可空布尔值。如果您想使用标准布尔值,请务必为其分配一个值。我很惊讶您没有在 Visual Studio 中使用该代码收到编译错误。