不能将 int 转换为 bool [英] Can't cast int to bool
问题描述
我面临的问题是,在我的情况下,C# 无法将数字 1 转换为 bool.在我的场景中 (bool)intValue
不起作用.我收到一个 InvalidCastException
.我知道我可以使用 Convert.ToBoolean(...)
但我只是想知道它不起作用.对此有什么解释吗?
I'm facing the problem that C# in my case can't cast the number 1 to bool. In my scenario (bool)intValue
doesn't work. I get an InvalidCastException
. I know I can use Convert.ToBoolean(...)
but I'm just wondering it doesn't work. Any explanation for this?
我的代码是
if (actualValueType.Name == "Boolean" || setValueType.Name == "Boolean")
{
if ((bool)actualValue != (bool)setValue)
...
}
推荐答案
int
和 bool
不能隐式转换(例如,与 C++ 相反).
int
and bool
can't be converted implicitly (in contrast to C++, for example).
这是一个语言设计者做出的明智决定,目的是在条件中使用数字时避免代码出错.条件需要显式地采用 boolean
值.
It was a concious decision made by language designers in order to save code from errors when a number was used in a condition. Conditions need to take a boolean
value explicitly.
不能写:
int foo = 10;
if(foo) {
// Do something
}
想象一下,如果开发者想将 foo 与 20 进行比较,但错过了一个等号:
Imagine if the developer wanted to compare foo with 20 but missed one equality sign:
if(foo = 20) {
// Do something
}
上面的代码可以编译并运行 - 并且副作用可能不是很明显.
The above code will compile and work - and the side-effects may not be very obvious.
对switch
进行了类似的改进:您不能从一种情况跌落到另一种情况 - 您需要明确的 break
或 return
.
Similar improvements were done to switch
: you cannot fall from one case to the other - you need an explicit break
or return
.
这篇关于不能将 int 转换为 bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!