如何在递归方法中检查相同变量的值?

时间:2015-02-04 12:27:51

标签: c# optimization recursion

我有一个变量,我想用递归方法检查。

要使其可见:

    private static void myMethod(/*variables*/){
        while (/* condition */) {
            foreach (/* condition */) {
                if (/* condition */) {
                    foreach (/*condition */) {
                        myMethod(/*variables*/);
                            }
                } else {
                /* THIS IS THE PART I AM ASKING FOR:
                 The if statement should ask if the Variable is NOT the same as before.*/

                        if (myMethodVariable != myMethodVariable[from before]){
                        // stuff to do.
}

所以myMethodVariable有一个值,它是一个char / string。我想检查一下这个值是否与以前一样,所以我可以检查重复项并立即打破循环。

有没有办法像myMethodVariable ['index']一样获取价值?由于变量是char / string,因此无法使用它。

抱歉我的英文。

2 个答案:

答案 0 :(得分:2)

您可以将变量作为参数传递给下一个调用:

private static void myMethod(/*variables*/, myMethodVariableFromBefore){
    while (/* condition */) {
        foreach (/* condition */) {
            if (/* condition */) {
                foreach (/*condition */) {
                    myMethod(/*variables*/, myMethodVariable);
                        }
            } else {
            /* THIS IS THE PART I AM ASKING FOR:
             The if statement should ask if the Variable is NOT the same as before.*/

                    if (myMethodVariable != myMethodVariableFromBefore){
                    // stuff to do.
}

答案 1 :(得分:2)

解决方案是存储入口点给定的值,然后将其与新值进行比较。

void MyMethod(int pipo)
{
    var oldPipo = pipo;

    //...//
    pipo = SomethingClever();  // Or something with recursive call.
    //...//

    if (oldPipo == pipo)
    {
        // we are done.
    }
}