Visual Basic和C#仅仅是学习基础知识和这些非常简单的几行代码的输出就把我搞糊涂了。
int x = 10;
int y = x++;
Console.WriteLine(x);
Console.WriteLine(y);输出是11,然后是10。我期望的是10,然后是11。这里我漏掉了什么?
发布于 2015-09-07 18:39:51
x++在其使用之后递增x (在您的示例中,在将其当前值赋给y之后)。另一方面,在使用x之前,++x会递增它。所以
int x = 10;
int y = ++x; // Note that the plus signs stand before x, not after!
Console.WriteLine(x);
Console.WriteLine(y);会导致
11
11
如果您想将x+1 (11)赋值给y,并将x留给10,那么请执行以下操作
int x = 10;
int y = x + 1;
Console.WriteLine(x);
Console.WriteLine(y);10
11个
发布于 2015-09-07 18:43:06
y = x++将首先赋值,然后递增。y = ++x将首先递增,然后赋值。在您的示例中,首先将x的值赋给y,然后将x递增到11。
因为int是一个value type (与引用类型相比),所以更改x的值不会影响分配给y的值。
int x = 10;
int y = x++; // Assigns the value of x to y (i.e. 10), THEN incrementing x to 11.
Console.WriteLine(x); // Writes the current value of x (i.e. 11).
Console.WriteLine(y); // Writes the current value of y (i.e. 10).https://stackoverflow.com/questions/32436634
复制相似问题