C# 不能隐式转换类型 bool?

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

Cannot implicitly convert type bool?

c#nullable

提问by user603007

I am trying to convert my nullable bool value and I am getting this error.

我正在尝试转换我的可为 null 的 bool 值,但出现此错误。

Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

For example:

例如:

public virtual bool? MyBool
  {
    get;
    set;
  }

if (!MyBool){}

采纳答案by SLaks

As the error states, you can't use a bool?in a conditional. (What would happen if it's null?)

正如错误所述,您不能bool?在条件中使用 a 。(如果是会发生什么null?)

Instead, you can write if (MyBool != true)or if (MyBool == false), depending on whether you want to include null. (and you should add a comment explaining that)

相反,您可以编写if (MyBool != true)if (MyBool == false),具体取决于您是否要包含null. (你应该添加一条评论来解释)

回答by NotMe

You have to use MyBool.Value

你必须使用 MyBool.Value

for example:

例如:

if (!MyBool.Value) { }

However, you should test that it does indeed have a value to begin with. This tests that MyBool has a value and it is false.

但是,您应该测试它确实具有开始的价值。这会测试 MyBool 是否有一个值并且它是假的。

if (MyBool.HasValue && !MyBool.Value) { }

Or you might really want the following that runs the code block if it either has not been assigned or has is false.

或者,如果尚未分配或 has 为 false,您可能真的想要运行代码块的以下内容。

if (!MyBool.HasValue || !MyBool.Value) { }

The question really boils down to whether you truly intended to have a nullable boolean variable and, if so, how you want to handle the 3 possible conditions of null, true or false.

问题实际上归结为您是否真的打算拥有一个可为空的布尔变量,如果是,您希望如何处理null, true or false.

回答by The Real Baumann

You need to check if it has a value. What do you want to do if MyBool == null?

您需要检查它是否具有值。如果你想做什么MyBool == null

if( MyBool.HasValue && !MyBool.Value ) // MyBool is false
if( MyBool.HasValue && MyBool.Value ) // MyBool is true
if( !MyBool.HasValue ) // MyBool is null