不能投INT为bool [英] Can't cast int to bool

查看:111
本文介绍了不能投INT为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临着C#在我的情况不能施放数字1到布尔的问题。在我的方案(布尔)的intValue 不起作用。我得到一个 InvalidCastException的。我知道我可以使用 Convert.ToBoolean(...),但我只是想知道这是行不通的。对于做任何解释?

我的code是

 如果(actualValueType.Name ==布尔|| setValueType.Name ==布尔)
{
   如果((布尔)actualValue!=(布尔)的setValue)
   ...
}


解决方案

INT 布尔不能隐式转换(与C ++中,例如)。

这是由语言设计者为了从错误中挽救code时的情况使用了一些做了一个 Concious酒店决定。条件需要采取布尔价值明确。

这是不可能写:

  INT富= 10;如果(富){
  // 做一点事
}

试想一下,如果开发商想用20比较富,但错过了等号:

 如果(富= 20){
  // 做一点事
}

以上code编译和工作 - 而副作用可能不会很明显。

类似的改进,都是为开关:你不能从一个案件下降到对方 - 你需要一个明确的收益

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?

My code is

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

解决方案

int and bool can't be converted implicitly (in contrast to C++, for example).

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.

It is not possible to write:

int foo = 10;

if(foo) {
  // Do something
}

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆