为什么我的变量在递归函数中不递增?

Why is my variable not incrementing in a recursive function?

好的,我的问题比较奇怪。我的老师要求我们编写一段代码来计算给定数组中有多少个偶数。我的代码如下:

static void Main(string[] args)
{
    int[] array = { 1, 2, 3, 4, 5, 6 };
    Console.WriteLine(NumOfEvens(array));
}

static int NumOfEvens(int[] array)
{
    return NumOfEvens(array, 0);
}

static int NumOfEvens(int[] array, int index)
{
    if (index == array.Length - 1)
    {
        if (array[index] % 2 == 0)
            return 1;
        else
            return 0;
    }
    if (array[index] % 2 == 0)
        return 1 + NumOfEvens(array, index++);
    else
        return NumOfEvens(array, index++);

}

然而,当我运行这个时,它会输出一个Stack Overflow。调试表明该函数根本没有增加我的索引变量。用“+1”替换增量似乎可以解决问题,但我很想知道这个问题的可能原因。

因为如果你在末尾写 ++ ,那么递增发生在赋值之后。它被称为“post 递增”,旧值先传递然后递增:

return NumOfEvens(array, index++);

如果写在开头那么变量会递增然后传值给函数这个叫做pre-increment:

return NumOfEvens(array, ++index);

return 1 + NumOfEvens(array, ++index);

Documentation

编辑:

灵感来自 Matt Burland 的评论 认为 index + 1 的意图更清楚,因为 index 的值实际上没有在其他任何地方使用,实际上不需要增加其当前值:

return NumOfEvens(array, index + 1);