使用数组索引时的操作顺序

JYe*_*ton 2 c# arrays operator-precedence

考虑这个循环:

int[] myArray = new int[10];

int myIndex = 0;
for (int i = 0; i < 10; i++)
{
    myArray[myIndex++] = myIndex;
    Console.WriteLine(myArray[i]);
}
Run Code Online (Sandbox Code Playgroud)

这会产生:

1
2
3
...
Run Code Online (Sandbox Code Playgroud)

因为myIndex是后递增的,并且首先评估右侧,所以数组索引0不应该包含0吗?

有人可以解释这个操作顺序误解吗?

Str*_*ior 5

不一定首先评估右侧.相近:

foo.Bar.Baz = a + b;
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,foo.Bar首先评估,然后调用a + bset_Baz方法将Baz属性设置为右侧评估的任何值.

所以在你的代码中,如果你把它分成几块,它看起来像这样:

var index = i;
// post-incremented in the original code means this comes after the line above,
// but not after the line below it.
i += 1; 
myArray[index] = i;
Run Code Online (Sandbox Code Playgroud)