编程语言
首页 > 编程语言> > 具有可选参数的C#递归函数

具有可选参数的C#递归函数

作者:互联网

我在递归函数上遇到可选参数问题

这是一个示例代码:

private static void RecursiveFunction(int x, int optional = 0)
{
    if (x < 5)
        RecursiveFunction(x + 1, optional++);
}

调用函数时:

RecursiveFunction(0);

我得到了以下结果(只需在即时窗口中调用此代码string.Format(“{0} – {1}”,x,可选):

"0 - 0"
"1 - 0"
"2 - 0"
"3 - 0"
"4 - 0"

我在这里错过了什么吗?谢谢!

解决方法:

改变自:

RecursiveFunction(x + 1, optional++);
//                               ^^

至:

RecursiveFunction(x + 1, ++optional);
//                       ^^

第一个执行操作然后增加可选.
第二个在增加可选项后执行操作.

MSDN开始:

++ var
var ++

The first form is a prefix increment operation. The result of the
operation is the value of the operand after it has been incremented.

The second form is a postfix increment operation. The result of the
operation is the value of the operand before it has been incremented.

标签:c,recursion,net-4-0,optional-parameters
来源: https://codeday.me/bug/20190713/1450534.html