不能隐式转换类型'布尔?以“布尔”。一个显式转换存在(是否缺少强制转换?)布尔、存在、类型、隐式

2023-09-04 09:43:02 作者:古董

错误:'布尔'不能隐式转换类型以布尔。一个显式转换存在(是否缺少强制转换?)

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

code:

Test obj = new Test();
obj.IsDisplay = chkDisplay.IsChecked;

但是当我使用,这意味着投在布尔那么就没有错误。

but when i use this means cast in bool then there is no error.

Test obj = new Test();
obj.IsDisplay = (bool) chkDisplay.IsChecked;

我需要知道的是,为什么要施放此布尔为BOO​​L。

I need to know that, why need to cast this bool to bool.

感谢

推荐答案

您已经声明器isChecked 布尔?可空<布尔> )。可空布尔值可以是 。现在问自己:如果器isChecked 为空,那么什么样的价值应该分配给 IsDisplay (只能取)?答案是,没有正确的答案。这里有一个隐式转换只能生产隐患,这也是为什么设计者决定只允许一个明确的转换,而不是一个隐含的。

You've declared IsChecked as a bool? (Nullable<bool>). A nullable boolean can be either true, false or null. Now ask yourself: If IsChecked was null, then what value should be assigned to IsDisplay (which can only take a true or false)? The answer is that there is no correct answer. An implicit cast here could only produce hidden trouble, which is why the designers decided to only allow an explicit conversion and not an implicit one.