[英]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.