CS0019 \t运算符'+ ='不能应用于'int'和'bool'类型的操作数
问题描述:
我目前正在编写一个简单的骰子游戏,并遇到一个让我困惑的错误,这是我的码。CS0019 t运算符'+ ='不能应用于'int'和'bool'类型的操作数
foreach (var die in Dice.rolls)
{
Console.WriteLine(die.ToString());
}
if (player.score += score >= goal)
{
playing = false;
Console.WriteLine("{0} has won the game!", player.name);
Console.WriteLine("Please press any key to end the game");
Console.ReadKey();
}
else
{
player.score += score;
}
我遇到的问题是该行:
if (player.score += score >= goal)
抛出了一个错误,告诉我,我不能用它在廉政局和布尔的,但所有的变量if语句是INT的。此外在这里几行:
player.score += score;
不给我任何错误。
答
可能是操作的优先级?尝试:
if ((player.score += score) >= goal)
虽然,在我看来,你应该: 一)把它分解成两行:
player.score += score;
if (player.score >= goal)
或b)将该行更改为:
if (player.score + score > goal)
现在,也许这是故意的,player.score最终会将得分加两次,如果它不是> = goal,那么它将作为if的一部分添加,然后作为else的主体。
答
这是运营商优先级的问题。比较运算符> =具有更高的优先级,所以本质上,您试图通过布尔比较score >= goal
的结果增加player.score
。
您可以使用括号来解决这个问题或简化您的表达式,例如,
player.score += score;
if (player.score >= goal)
你可以看一下这里https://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx
更多信息,您不能在同一行做这两种操作。只需先添加分数,然后再进行比较。你告诉编译器要做的是解决score> = goal并将其添加到player.score中,从而产生错误。 –