简体   繁体   English

铸造可空的布尔到布尔

[英]Cast nullable bool to bool

I have an object AlternateName.IsMaidenName 我有一个对象AlternateName.IsMaidenName

I want to cast that to a checkbox - IsMaidenName 我想把它转换成一个复选框--IsMaidenName

It wont let me cast that as it says Cannot convert source type nullable to target type bool. 它不会让我按照它所说的无法转换源类型可以为目标类型bool。

I've had this issue in other spots within our application but I wanted to throw it out there for a better way to handle these issues. 我在我们的应用程序中的其他位置遇到过这个问题但是我想把它扔出去以便更好地处理这些问题。

IsMaidenNameChecked = AlternateName.IsMaidenName;

It is quite logical that you cannot cast a nullable bool to a bool, since, what value should the bool have, when the nullable contains null ? 你不能将一个可空的bool强制转换为bool是合乎逻辑的,因为当nullable包含null时,bool应该有什么值?

What I would do, is this: 我会做的是这样的:

IsMaidenNameChecked = AlternateName.IsMaidenName ?? false;
IsMaidenName.Checked = AlternateName.IsMaidenName.GetValueOrDefault();

请参阅: http//msdn.microsoft.com/en-us/library/72cec0e0.aspx

You probably want to do something like: 你可能想做类似的事情:

 IsMaidenNameChecked = AlternateName.IsMaidenName.GetValueOrDefault ();

See Nullable.GetValueOrDefault () , or you can use the overload that includes an explicit default. 请参阅Nullable.GetValueOrDefault() ,或者您可以使用包含显式默认值的重载。

Checkboxes and Nullable<bool> both have three states: "true", "false", and "missing". 复选框和Nullable<bool>都有三种状态:“true”,“false”和“missing”。

But you're trying to store the value in an intermediate bool variable which has no way to handle "missing". 但是你试图将值存储在一个无法处理“丢失”的中间bool变量中。

Try changing your bool variable to also be bool? 尝试将bool变量更改为bool? .

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

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