在C#中,+=和=+有什么区别吗?

5

如果我出发

variable1 =+ variable2
variable1 += variable2

我对变量1得到了同样的结果。那么有什么区别吗?
5个回答

19

区别在于你的观察结果是不正确的,variable1 =+ variable2并没有将variable2加到variable1中,而是将variable1设置为等于variable2。该行代码实际上应该是variable1 = +variable2或者简单地variable1 = variable2.

考虑下面这段代码:

int a = 10;
int b = 20;

a =+ b;
a += b;

在这个过程的结尾,a等于40。它被初始化为10,b被初始化为20,a被设置等于b,然后b加上a


5
是的,两者有区别。
int x = 0; 

x += 1; --> x = x + 1; (you are adding 1 to x)

x =+ 1; --> x = +1; (you are assigning x a value)

3

是的,使用玩具示例,我展示了它们之间的区别。

  • In the case of variable1 =+ variable2 you're effectively computing

    variable1 = 0 + variable2
    

    or simply

    variable1 = variable2
    
  • In the case of variable1 += variable2 you're effectively computing

    variable1 = variable1 + variable2
    

2
也许最好声明一下,在C#中没有=+运算符。但是你可以使用一元+来表示一个正数(总是多余的,但为了完整性而包括)。
为了回答完整,x += y与x = x + y相同。

0
你可能得到了相同的结果,因为你正在同时运行它们。
        int One = 50;
        int Two = 65;
        One += Two;
        Two =+ One;
        Console.WriteLine(One);
        Console.WriteLine(Two);

这两行代码会得到相同的结果,因为 int One 已经等于 One + Two,然后你将 One 赋值给了 Two。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接