无法将类型'int'隐式转换为'bool',我不明白 [英] cannot implicitly convert type 'int' to 'bool' and i dont understand

查看:560
本文介绍了无法将类型'int'隐式转换为'bool',我不明白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用球和蝙蝠创建一款破砖游戏.我正在努力使球像在墙壁上那样从球棒上反射出来,但是我尝试的方式似乎是错误的,或者是我不太了解的事情:

I'm trying to create a brick breaker type game with a ball and bat. I'm working on making the ball reflect off the bat like it does with the walls but i the way i am trying it seems to be wrong or is something i do not understand very well:

private int x;
private int batx;
if (x = batx)

收到消息后无法将类型'int'隐式转换为'bool'

comes up with the message cannot implicitly convert type 'int' to 'bool'

我刚开始使用C#,所以我不太了解该怎么做.还有另一种方法可以使球从球棒上反射出来吗?

i just started C# so i don't really understand what to do. is there another way i can make the ball reflect off the bat?

推荐答案

ekad在这里给出了正确的答案,但这是一个学习的机会:

ekad gave the correct answer here, but since this is an opportunity for learning:

if 语句在其括号内需要一个 bool 值,这就是为什么您可以使用以下内容的原因:

if statements expect a bool value inside their parentheses, which is why you can have things like:

if (true)

if (false)

但是

if (1)

没有任何意义.当您进行比较( == )时,例如:

doesn't make any sense. When you do a comparison (==) like:

if (a == b)

a b 进行等效性比较,并且该语句的计算结果为 true false .这可能已经对您有意义.

a is compared to b for equivalence, and the statement will evaluate to either true or false. This probably makes sense to you already.

赋值( = )也会求值,并且该值是左操作数的值.返回的 type 是左操作数的类型.

Assignment (=), however, also evaluates to a value, and the value is the value of the left operand. The type returned is the type of the left operand.

batx = 5;
if (x = batx) {

本质上评估为

if (5)

如前所述,这没有任何意义(无论如何,在C#中,这在C中确实是有道理的).我输入所有内容的原因是它解释了您得到的编译器错误.

Which, as said before, doesn't make sense (in C#, anyway -- this does make sense in C). The reason why I typed all that out is that it explains the compiler error you got.

不能将类型'int'隐式转换为'bool'

编译器希望在括号内找到一条计算结果为 bool 的语句.相反,它找到一条计算结果为 int 的语句.

The compiler expected to find a statement which evaluates to a bool inside the parentheses. Instead, it found a statement that evaluates to int.

这篇关于无法将类型'int'隐式转换为'bool',我不明白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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