增量运算符如何与数组一起使用?

How does increment operator work with arrays?

这是让我感到困惑的代码:

var array = new int[5];
array[0] = 1;
array[0]++;
Console.WriteLine(array[0]);  //'2' is printed

我不明白为什么数组的项目会递增。据我了解,应该会发生以下情况:

1st line: I create an array with a capacity for 5 ints.

2nd line: I put '1' into 0 index of this array

3rd line: I retrieve item from index 0 and increment it by 1

4th line: I print the item at index 0

第三行是这里的关键。我不明白数字“2”是如何写入数组的。我只是在阅读项目并递增它。

array[0]++;(大致)等同于array[0] += 1;

因此值被写回数组位置。

这是一个副作用,需要注意一个序列问题:

int y = array[0]++;       // now y == 1 and array[0] == 2

int y = (array[0] += 1);  // now y == 2 and array[0] == 2

在 C# 中,递增和递减运算符作用于:

  • 变量
  • 属性 访问
  • 索引器访问(您的情况)

生成的代码还知道将值存储回何处。

如果运算符只增加一个值,即使 myVariable++ 也不会做任何事情。

有关详细信息,请参阅 Arithmetic Operators

工作原理如下:

array[0]++;

首先,评估"array[0]"。

其次,增量是在 "array[0]" 保存的值上完成的。

例如,如果你写:

if (array[0]++ == 2) DoSomething();

首先,评估条件 (array[0] == 2)。

其次,数组[0]递增。

三、执行下一条指令

但是如果你写:

if (++array[0] == 2) DoSomething();

首先,数组[0]递增。

其次,评估条件(数组[0] == 2)。

三、执行下一条指令

如果在一条指令中只写一个增量:

++x;

x++;

它做同样的事情。