简体   繁体   中英

Cast nullable bool to bool

I have an object AlternateName.IsMaidenName

I want to cast that to a checkbox - IsMaidenName

It wont let me cast that as it says Cannot convert source type nullable to target type 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 ?

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.

Checkboxes and Nullable<bool> both have three states: "true", "false", and "missing".

But you're trying to store the value in an intermediate bool variable which has no way to handle "missing".

Try changing your bool variable to also be bool? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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