Cast nullable bool to bool
I have an object AlternateName.IsMaidenName
I w开发者_Python百科ant 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();
See: 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?.
加载中,请稍侯......
精彩评论