c# - 如何在 C# 中将 Cast null 类型转换为 Bool?

标签 c# casting boolean nullable

我有一个可以为 null 的 bool (bool?) 变量,它包含一个 null 值。又一个纯 bool 类型的变量,我试图将可为 null 的 bool 转换为 bool。但是我遇到了一个错误“Nullable object must have a value.

我的C#代码是

bool? x = (bool?) null;
bool y = (bool)x;

最佳答案

使用x.GetValueOrDefault() 将默认值(false for System.Boolean)分配给yx.HasValue == false 的情况下。

或者,您可以使用空合并运算符 (??),如下所示:

bool y = x ?? false;

关于c# - 如何在 C# 中将 Cast null 类型转换为 Bool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34585362/

相关文章:

python - numpy boolean 数组内存溢出

MySQL 查询过滤包含搜索字符串中任何单词的记录

c# - 洪水填充算法无限循环

c# - c# 如何处理嵌套(泛型)类型?

.net - 从数据库检索数据时进行强制转换还是转换?

c++ - "Ambigous"等效转换 - 我可以让编译器只选择任何一个吗?

rust - rust 类型类型转换选项

c++ - 如何在 C++ 中使用正态分布生成真值或假值

c# - 将 img 从 url 加载到 WinForms 中的 DataGridView

java - C#/Java 压缩 JPG 图像