不能投给bool ?

时间:2021-09-04 02:57:28

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?

我面对的问题是c#在我的情况下不能把数字1投给bool。在我的场景中(bool)intValue不起作用。我得到一个InvalidCastException。我知道我可以使用Convert.ToBoolean(…)但我只是觉得它不起作用。任何解释吗?

My code is

我的代码是

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

11 个解决方案

#1


38  

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

int和bool不能隐式地转换(例如,与c++相比)。

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:

设想一下,如果开发人员想要比较foo和20,但是忽略了一个等号:

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.

类似的改进也有了改变:你不能从一种情况降到另一种情况——你需要明确的休息或返回。

#2


52  

There's no need to cast:

没有必要投:

bool result = intValue == 1;

From the docs:

从文档:

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

bool的加入使得编写自文档化代码变得更加容易。

a bool value is either true or false

bool值要么为真,要么为假。

1.2.1 Predefined Types (C#)

1.2.1预定义类型(c#)

#3


31  

bool b = Convert.ToBoolean(0);

Will convert 0 and null to false and anything else to true.

将0和null转换为false,并将其他内容转换为true。

#4


0  

In other languages, false is equivalent to 0 and true is equivalent to 1, but this is not possible in the C# language.

在其他语言中,false等于0,true等于1,但是在c#语言中这是不可能的。

#5


0  

In C#, bool is actually a Boolean struct, so it's not just represented as a 1 or 0 internally. It seems like the creators of the language went for an explicit over implicit approach overall with the language. To accomplish what you're trying to do (to effectively cast 1 to true and 0 to false), do this:

在c#中,bool实际上是一个布尔结构,所以它不只是在内部表示为1或0。似乎语言的创造者在语言的整体上对隐含的方法进行了明确的阐释。为了完成你想要做的事情(有效地将1转换为true, 0为false),这样做:

if (intValue == 1) {
    // do something
} else if (intValue == 0) {
    // do something else
} else {
    // invalid bool
}

You could also drop the last else clause and do the typical C-language thing and let intValue == 0 be equivalent to false and anything else is true.

您还可以删除最后一个else子句,并执行典型的c语言的操作,让intValue == 0等于false,其他任何事情都是正确的。

#6


0  

Probably repeating others here but you cant cast int to bool because int is not a bool. It is an int. Who would have thought? ;-)

很可能在这里重复,但是你不能把int变成bool,因为int不是bool。这是一个整数,谁会想到呢?:-)

You need to create a new bool based on your int value, and the already posted "myvar != 0" seems good enough.

您需要根据您的int值创建一个新的bool,并且已经发布的“myvar != 0”似乎已经足够好了。

Also where do you get your exception? Running the following code will most certainly produce a compiler error:

你在哪里有例外?运行以下代码肯定会产生一个编译器错误:

int myIntValue = 0;
bool myBoolValue = (bool)myIntValue;

You must be doing some generic stuff which is not shown in your question.

你必须做一些没有在你的问题中显示出来的通用的东西。

#7


0  

"In other languages, false is equivalent to 0 and true is equivalent to 1, but this is not possible in the C# language."

“在其他语言中,false等于0,true等于1,但是在c#语言中这是不可能的。”

I have to admit I thought false was zero and true was !false....

我不得不承认我认为错误是零,真的是!假....

int fred = 2;

if (fred == true)
{
    printf("fred is true");
}

will certainly print fred is true

肯定会打印出fred是真的吗?

#8


0  

if you want to cast two values variable into bool like var that holds (1 and 2 and want to return 1 for false and 2 for true ) i suggest :

如果你想将两个值变量转换成bool,比如var(1和2,并希望返回1为false, 2为true),我建议:

//in the end of method or something :
return w == 2;

#9


0  

You could use the ternary operator like below, instead of a cast. bool b = true; int i = 1;

你可以使用下面的三元运算符,而不是cast。bool b = true;int i = 1;

// bool to int
i = b == true ? 1 : 0;
// int to bool
b = i > 0 ? true : false;

#10


0  

If all you want is not to have to type the != 0 in if (foo != 0), you could make an extension method for the int type and do something like if (foo.IsNonZero()).

如果您想要的是不需要键入!= 0,那么您可以为int类型创建一个扩展方法,并做一些类似的事情(foo. isnonzero())。

If C# allowed for extension properties, you would be able to write if (foo.IsNonZero) without the parentheses, which in my opinion would read more clearly than the original if (foo != 0), but sadly, that is currently not the case.

如果c#允许扩展属性,那么您就可以在没有括号的情况下编写If (foo. isnonzero),在我看来,这比If (foo != 0)更清晰,但遗憾的是,目前情况并非如此。

You're probably better off with the previously suggested Convert.ToBoolean(foo) either way, though.

不过,您最好还是使用前面建议的Convert.ToBoolean(foo)方法。

#11


0  

I'm working on a pathfinding, for learning purposes. I need to randomly block some nodes as walkable/blocked.

为了学习目的,我正在研究一个寻路。我需要随机地阻塞一些节点作为可步行/阻塞。

Here's a simple solution I came up with:

下面是我提出的一个简单的解决方案:

int block = Random.Range(0, 10) + 1;
node.blocked = (block % 2 == 0) ? true : false;

#1


38  

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

int和bool不能隐式地转换(例如,与c++相比)。

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:

设想一下,如果开发人员想要比较foo和20,但是忽略了一个等号:

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.

类似的改进也有了改变:你不能从一种情况降到另一种情况——你需要明确的休息或返回。

#2


52  

There's no need to cast:

没有必要投:

bool result = intValue == 1;

From the docs:

从文档:

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

bool的加入使得编写自文档化代码变得更加容易。

a bool value is either true or false

bool值要么为真,要么为假。

1.2.1 Predefined Types (C#)

1.2.1预定义类型(c#)

#3


31  

bool b = Convert.ToBoolean(0);

Will convert 0 and null to false and anything else to true.

将0和null转换为false,并将其他内容转换为true。

#4


0  

In other languages, false is equivalent to 0 and true is equivalent to 1, but this is not possible in the C# language.

在其他语言中,false等于0,true等于1,但是在c#语言中这是不可能的。

#5


0  

In C#, bool is actually a Boolean struct, so it's not just represented as a 1 or 0 internally. It seems like the creators of the language went for an explicit over implicit approach overall with the language. To accomplish what you're trying to do (to effectively cast 1 to true and 0 to false), do this:

在c#中,bool实际上是一个布尔结构,所以它不只是在内部表示为1或0。似乎语言的创造者在语言的整体上对隐含的方法进行了明确的阐释。为了完成你想要做的事情(有效地将1转换为true, 0为false),这样做:

if (intValue == 1) {
    // do something
} else if (intValue == 0) {
    // do something else
} else {
    // invalid bool
}

You could also drop the last else clause and do the typical C-language thing and let intValue == 0 be equivalent to false and anything else is true.

您还可以删除最后一个else子句,并执行典型的c语言的操作,让intValue == 0等于false,其他任何事情都是正确的。

#6


0  

Probably repeating others here but you cant cast int to bool because int is not a bool. It is an int. Who would have thought? ;-)

很可能在这里重复,但是你不能把int变成bool,因为int不是bool。这是一个整数,谁会想到呢?:-)

You need to create a new bool based on your int value, and the already posted "myvar != 0" seems good enough.

您需要根据您的int值创建一个新的bool,并且已经发布的“myvar != 0”似乎已经足够好了。

Also where do you get your exception? Running the following code will most certainly produce a compiler error:

你在哪里有例外?运行以下代码肯定会产生一个编译器错误:

int myIntValue = 0;
bool myBoolValue = (bool)myIntValue;

You must be doing some generic stuff which is not shown in your question.

你必须做一些没有在你的问题中显示出来的通用的东西。

#7


0  

"In other languages, false is equivalent to 0 and true is equivalent to 1, but this is not possible in the C# language."

“在其他语言中,false等于0,true等于1,但是在c#语言中这是不可能的。”

I have to admit I thought false was zero and true was !false....

我不得不承认我认为错误是零,真的是!假....

int fred = 2;

if (fred == true)
{
    printf("fred is true");
}

will certainly print fred is true

肯定会打印出fred是真的吗?

#8


0  

if you want to cast two values variable into bool like var that holds (1 and 2 and want to return 1 for false and 2 for true ) i suggest :

如果你想将两个值变量转换成bool,比如var(1和2,并希望返回1为false, 2为true),我建议:

//in the end of method or something :
return w == 2;

#9


0  

You could use the ternary operator like below, instead of a cast. bool b = true; int i = 1;

你可以使用下面的三元运算符,而不是cast。bool b = true;int i = 1;

// bool to int
i = b == true ? 1 : 0;
// int to bool
b = i > 0 ? true : false;

#10


0  

If all you want is not to have to type the != 0 in if (foo != 0), you could make an extension method for the int type and do something like if (foo.IsNonZero()).

如果您想要的是不需要键入!= 0,那么您可以为int类型创建一个扩展方法,并做一些类似的事情(foo. isnonzero())。

If C# allowed for extension properties, you would be able to write if (foo.IsNonZero) without the parentheses, which in my opinion would read more clearly than the original if (foo != 0), but sadly, that is currently not the case.

如果c#允许扩展属性,那么您就可以在没有括号的情况下编写If (foo. isnonzero),在我看来,这比If (foo != 0)更清晰,但遗憾的是,目前情况并非如此。

You're probably better off with the previously suggested Convert.ToBoolean(foo) either way, though.

不过,您最好还是使用前面建议的Convert.ToBoolean(foo)方法。

#11


0  

I'm working on a pathfinding, for learning purposes. I need to randomly block some nodes as walkable/blocked.

为了学习目的,我正在研究一个寻路。我需要随机地阻塞一些节点作为可步行/阻塞。

Here's a simple solution I came up with:

下面是我提出的一个简单的解决方案:

int block = Random.Range(0, 10) + 1;
node.blocked = (block % 2 == 0) ? true : false;