[英]recursive function in c# get a parameter
我正在尝试使用此功能获取参数...
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 ...我无法得到...谢谢大家
您需要通过acc通过引用。 即使用: public static int subsumer(string id,ref int acc,SqlConnection connection) {
通过返回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;
}
附带说明,递归查询不是一个好的设计选择。 在堆栈上的每个调用都打开读取器的情况下进行递归查询会更糟。 不使用查询参数也是一件坏事。
该方法在开始时递增,在结束时递减,因此,看来您总是会以acc的初始调用值(在您的情况下为0)结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.