[英]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 每个周期参数acc
都会增加并进行调试,我看到在我的情况下它达到了值3,但是在最后的递归中,我总是得到0 ...我无法得到...谢谢大家
You need to pass acc by reference. 您需要通过acc通过引用。 Ie use: public static int subsumer(string id,ref int acc,SqlConnection connection) {
即使用: 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. 通过返回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;
}
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)结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.