CS0019运算符'+ ='不能应用于'int'和'bool'类型的操作数

时间:2017-04-24 23:11:28

标签: c# runtime-error operators

我目前正在编写一个简单的骰子游戏,我遇到了一个让我困惑的错误,这是我的代码。

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)

抛出错误告诉我我不能在int和bool上使用它,但if语句中的所有变量都是int。此外还有几行:

player.score += score;

没有给我任何错误。

2 个答案:

答案 0 :(得分:3)

可以优先运营吗?尝试:

if ( (player.score += score) >= goal)

虽然,在我看来你应该: a)将其分为两行:

player.score += score;
if (player.score >= goal)

或b)将行更改为:

if (player.score + score > goal)

就目前而言,也许这是故意的,如果不是> =目标,则player.score最终将得分加两次,因为它会作为if的一部分添加,然后作为正文别的。

答案 1 :(得分:1)

这是运营商优先权的问题。比较运算符> =具有更高的优先级,因此实际上您试图通过布尔比较player.score的结果递增score >= goal

您可以使用括号来解决此问题或简化表达,例如

player.score += score;
if (player.score >= goal)

您可以在此处查看更多信息https://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx

相关问题