使用数组索引时的操作顺序
考虑这个循环:
int[] myArray = new int[10];
int myIndex = 0;
for (int i = 0; i < 10; i++)
{
myArray[myIndex++] = myIndex;
Console.WriteLine(myArray[i]);
}
这会产生:
1
2
3
...
因为 myIndex 是后递增的,并且首先评估右侧,所以数组索引 0 不应该包含 0 吗?
有人能为我解释一下这种操作顺序的误解吗?
Consider this loop:
int[] myArray = new int[10];
int myIndex = 0;
for (int i = 0; i < 10; i++)
{
myArray[myIndex++] = myIndex;
Console.WriteLine(myArray[i]);
}
This yields:
1
2
3
...
Because myIndex is post-incremented, and the right side is evaluated first, shouldn't the array index 0 contain 0?
Can someone explain this order-of-operations misunderstanding for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不一定首先评估右侧。类似:
在上面的代码中,首先评估
foo.Bar
,然后评估a + b
,然后调用set_Baz
方法来设置Baz 属性为右侧评估的任何内容。所以在你的代码中,如果你把它分成几部分,它看起来像这样:
The right side isn't necessarily evaluated first. Similar to:
In the above code,
foo.Bar
is evaluated first, thena + b
, then theset_Baz
method is called to set the Baz property to whatever is evaluated on the right.So in your code, if you break it into pieces, it looks like this:
第一次运行:
myIndex++
在myArray[myIndex++]
之后执行,但任何后续调用都具有已经递增的变量。first run:
myIndex++
gets executed aftermyArray[myIndex++]
, but any subsequent calls with have the already incremented variable.myIndex++ 在设置值之前执行,因为数组索引优先,因此它知道将值设置为哪个数组索引。
The myIndex++ is executing before the value is being set because the array index takes precident so it knows what array index to set the value to.
...
...相当于...
The...
...is equivalend to...
根据优先级,首先计算
myIndex++
,然后是左侧,最后是赋值运算符The
myIndex++
is evaluated first, followed by the left side and finally the assign operator, according to precedence