简体   繁体   中英

recursive function in c# get a parameter

I'm trying to get a parameter with this function...

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;
}

each cycle the parameter acc will increment and debugging i see that in my case it reach value 3, but in the final recursion i get always 0...i can't get it...thank you all

You need to pass acc by reference. Ie use: public static int subsumer(string id,ref int acc,SqlConnection connection) {

By returning acc - 1 , you are decrementing f returned by your recursive call and I don't think that's what you expect.

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;
}

On a side note, querying recursively isn't a good design choice. Querying recursively with readers open for each call on the stack is even worse. Not using query parmeters is also a bad thing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM