无法将类型'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
.