c#
  • recursion
  • 2015-04-01 139 views 0 likes 
    0

    我试图让这个函数中的参数...递归函数得到一个参数

    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 ...我无法得到它...谢谢大家

    +0

    你是什么意思'参数'?此外,为什么你使用字符串连接而不是使用正确的参数化查询?输入中的一个奇怪的字符会导致问题。更有趣的输入可能是'1; DROP TABLE COMMON_RELATION;'' – 2015-04-01 14:29:53

    +4

    你是如何调用函数的?你有没有在调试器中检查它,确保你的逻辑是正确的? – 2015-04-01 14:31:16

    +0

    你的功能假设要做什么?总数还是最大值? ,因为我看到你的循环中只有分配 没有增量 – 2015-04-01 14:43:44

    回答

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

    在附注中,递归查询不是一个好的设计选择。对于堆栈中的每个调用打开的读者递归地查询更加糟糕。不使用查询参数也是一件坏事。

    +0

    好吧,现在我终于明白了!我知道递归查询不是一个很好的选择,我不是一个专家开发人员,我面临与wordnet和一些其他的东西,它不适当的“你好世界”的句子相似性。 我如何使用查询参数? – Lorenzo 2015-04-01 15:06:51

    +0

    只是谷歌,很多关于它的东西。 – 2015-04-01 15:10:34

    +0

    @Lorenzo,搜索现有问题或发布一个包含您的查询的新问题,并询问您如何对其进行参数化。 – Guillaume 2015-04-01 15:39:28

    2

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

    +6

    该函数返回'acc-1'因此不应该需要使用'ref'(除非OP调用不正确)。 – 2015-04-01 14:30:53

    +0

    我这么叫 int fuffa = DistanzaParole.subsumer(“n#00004123”,0,连接); – Lorenzo 2015-04-01 14:45:53

    0

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

    +0

    它不应该增加: f = subsumer(leggsyn [“id_target”]。ToString(),acc,connection); if(acc <= f) { acc = f; }? – Lorenzo 2015-04-01 14:52:46

    +0

    当acC++时它会增加,然后当没有记录时,它会返回acc--,这意味着它会返回相同的值。 – 2015-04-01 14:58:31

    相关问题