c#中的递归函数得到一个参数

时间:2015-04-01 14:26:27

标签: c# recursion

我正在尝试使用此函数获取参数...

public static int subsumer(string id,int acc,SqlConnection connection) 
{
    acc++;
    SqlCommand cercas = new SqlCommand("select * from common_relation where id_source ='" + id + "' AND type='@' ", connection);
    SqlDataReader leggsyn = null;
    leggsyn = cercas.ExecuteReader();

    int f = 0;
    while (leggsyn.Read()) 
    {
        f=  subsumer(leggsyn["id_target"].ToString(),acc,connection);
        if (acc <= f) 
        { 
            acc = f; 
        }  
    }

     //siamo arrivati alla fine
    return acc-1;
}

每个循环参数acc将递增并调试我看到在我的情况下它达到值3,但在最后的递归中我总是0 ...我无法得到它...谢谢所有

3 个答案:

答案 0 :(得分:2)

您需要通过引用传递acc。即使用:public static int subsumer(string id,ref int acc,SqlConnection connection) {

答案 1 :(得分:1)

通过返回acc - 1,您递归递归调用返回f,我认为这不是您所期望的。

public static int subsumer(string id,int acc,SqlConnection connection) 
{
    SqlCommand cercas = new SqlCommand("select * from common_relation where id_source ='" + id + "' AND type='@' ", connection);
    SqlDataReader leggsyn = null;
    leggsyn = cercas.ExecuteReader();

    int f = 0;
    while (leggsyn.Read()) 
    {
        f=  subsumer(leggsyn["id_target"].ToString(),acc + 1,connection);
        if (acc <= f) 
        { 
            acc = f; 
        }  
    }

     //siamo arrivati alla fine
    return acc;
}

另一方面,递归查询不是一个好的设计选择。对于堆栈上的每个调用打开的读取器递归查询更糟糕。不使用查询参数也是一件坏事。

答案 2 :(得分:0)

该方法在开始时递增,在结束时递减,因此您似乎总是以acc的初始调用值结束(在您的情况下为0)。

相关问题