简体   繁体   English

C#为可空布尔值赋值

[英]c# assign value for nullable boolean

I am trying to play around with the ?: Operator on assigning a value into a nullable boolean variable. 我正在尝试将?:运算符分配给可为空的布尔变量。

This the original code which works fine 这是原始代码,可以正常工作

bool? result;
var condition = 3;

if (condition == 1)
    result = true;
else if (condition == 2)
     result = false;
else result = null;

After I change the code, it hit an error, and I fix it after searching the internet 更改代码后,它遇到错误,我在搜索互联网后将其修复

// before (error occur)
result = condition == 1 ? true : (condition == 2 ? false : null);

// after (fixed error)
result = condition == 1 ? true : (condition == 2 ? false : (bool?)null); 
// *or
result = condition == 1 ? true : (condition == 2 ? (bool?)false : null);

I understand that both expressions have to be of the same type, but why it only required to convert one expression but not all of the expression? 我知道两个表达式必须具有相同的类型,但是为什么只需要转换一个表达式却不转换所有表达式呢? which make me confused. 这让我感到困惑。

from my understanding bool and bool? 从我的理解bool and bool? or bool? and null 还是bool? and null bool? and null should be still considered the not same type, but it works in the situation. bool? and null应该仍然被认为是不相同的类型,但是在这种情况下可以使用。

Any advice to this will be appreciated. 任何建议,将不胜感激。 Thanks. 谢谢。

In a ternary conditional operator, the compiler requires that each of the possible assigned values are of the same type. 在三元条件运算符中,编译器要求每个可能的赋值都是同一类型。

In the segment (condition == 2 ? false : null) , the two possible values are false and null . 在段中(condition == 2 ? false : null) ,两个可能的值为falsenull The compiler sees false as a bool , so it will error as null isn't a valid alternate value for a bool . 编译器将false视为bool ,因此会出错,因为null不是bool值的有效替代值。

By prefixing either with (bool?) , you make it clear that you're actually assigning a nullable boolean, making the compiler happy because it knows both values are indeed the same type. 通过使用(bool?)作为前缀,您可以清楚地知道实际上是在分配一个可为空的布尔值,这使编译器感到满意,因为它知道两个值确实是同一类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM