问题
I have some code
static void Main(string[] args)
{
int j = 0;
for (int i = 0; i < 10; i++)
j = j++;
Console.WriteLine(j);
}
Why answer is 0 ?
回答1:
This is because of the way the ++ increment works. The order of operations is explained in this MSDN article This can be seen here (somebody please correct me if I am reading the spec on this one wrong :)):
int j = 2;
//Since these are value objects, these are two totally different objects now
int intermediateValue = j;
j = 2 + 1
//j is 3 at this point
j = intermediateValue;
//However j = 2 in the end
Since it is a value object, the two objects (j
and intermediateValue
) at that point are different. The old j was incremented, but because you used the same variable name, it is lost to you. I would suggest reading up on the difference of value objects versus reference objects, also.
If you had used a separate name for the variable, then you would be able to see this breakdown better.
int j = 0;
int y = j++;
Console.WriteLine(j);
Console.WriteLine(y);
//Output is
// 1
// 0
If this were a reference object with a similar operator, then this would most likely work as expected. Especially pointing out how only a new pointer to the same reference is created.
public class ReferenceTest
{
public int j;
}
ReferenceTest test = new ReferenceTest();
test.j = 0;
ReferenceTest test2 = test;
//test2 and test both point to the same memory location
//thus everything within them is really one and the same
test2.j++;
Console.WriteLine(test.j);
//Output: 1
Back to the original point, though :)
If you do the following, then you will get the expected result.
j = ++j;
This is because the increment occurs first, then the assignment.
However, ++ can be used on its own. So, I would just rewrite this as
j++;
As it simply translates into
j = j + 1;
回答2:
As the name says, post-increment increments after the value has been used
y = x++;
According to the C# Language Specification this is equivalent to
temp = x;
x = x + 1;
y = temp;
Applied to your original problem it means that j
remains the same after these operations.
temp = j;
j = j + 1;
j = temp;
You can also use pre-increment, which does the opposite
x = x + 1;
y = x;
or
y = ++x;
See Postfix increment and decrement operators on MSDN
来源:https://stackoverflow.com/questions/9863736/explaining-post-increment-in-c-sharp