c# - 无法将 int 转换为 bool

标签 c# casting int boolean

我面临的问题是,在我的例子中,C# 无法将数字 1 转换为 bool。在我的场景中 (bool)intValue 不起作用。我得到一个 InvalidCastException。我知道我可以使用 Convert.ToBoolean(...) 但我只是想知道它不起作用。对此有什么解释吗?

我的代码是

if (actualValueType.Name == "Boolean" || setValueType.Name == "Boolean")
{
   if ((bool)actualValue != (bool)setValue)
   ...
}

最佳答案

不需要强制转换:

bool result = intValue == 1;

来自文档:

The inclusion of bool makes it easier to write self-documenting code

a bool value is either true or false

1.2.1 Predefined Types (C#)

关于c# - 无法将 int 转换为 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6571312/

相关文章:

c# - Hololens 2 轻击和头部移动在 Unity 中有效,但在 HoloLens 上无效

c# - 如何在 mvc 4.5 中验证选择下拉列表?

python - 从字符串转换为 int python 的麻烦

c# - 从 File.ReadAllBytes (byte[]) 中删除字节顺序标记

php - 为什么 PHP 和 JavaScript 在处理八进制和十六进制数时会出现问题?

c++ - boost::phoenix::static_cast_ 编译错误

c - 二进制操作数无效/(有 ‘float *’ 和 ‘int’ )?

用2个函数计算

python - "is"运算符对整数的行为异常

具有多个返回参数的 C# 方法