2012-09-26 38 views
-1

Iwrote C#代碼,它似乎正確,我錯誤告訴並非所有的代碼路徑返回一個值

public static BCSMappedTable GetMappedTable(string p_ListName) 
    { 
     List<BCSDataBase> ConnexionList = BCSManagement.GetAllDataBases(); 
     bool found = false; 
     foreach (BCSDataBase connexion in ConnexionList) 
     { 
      foreach (BCSMappedTable tabList in connexion.GetMappedTables()) 
      { 
       if (tabList.getListeName().Equals(p_ListName)) 
       { 
        found = true; 
        return tabList; 
       } 
      } 
     } 
     if (found) 
      return new BCSMappedTable(); 
    } 

,但這個錯誤繼續出現

error : not all code paths return a value 

,我沒有線索,爲什麼!我瘦,我總是返回所需的值

+1

他們說什麼。你是否意指'如果(!發現)'接近尾聲?因爲每當'found'成立時,你已經在例程中早些返回了,所以'if(找到)'在結尾再次是多餘的。 –

回答

7

在函數結束時,如果found是假的,你沒有返回路徑...

當你有你的循環內return聲明中,函數將在找到該項目後立即退出,因此您不需要found變量。你可以像去:

public static BCSMappedTable GetMappedTable(string p_ListName) 
{ 
    List<BCSDataBase> ConnexionList = BCSManagement.GetAllDataBases(); 
    foreach (BCSDataBase connexion in ConnexionList) 
    { 
     foreach (BCSMappedTable tabList in connexion.GetMappedTables()) 
     { 
      if (tabList.getListeName().Equals(p_ListName)) 
      { 
       // return as soon as the item is found 
       return tabList; 
      } 
     } 
    } 

    // this code won't be executed if the item was found before... 
    return new BCSMappedTable(); 
} 
2

因爲你到底有

if (found) 
      return new BCSMappedTable(); 

如果什麼它不是發現了什麼?

事情是,它wouldnt那裏,因爲發現被設置爲true時,你從函數返回 - 所以,也,這一切都需要說的是

return new BCSMappedTable(); 
0

實施

if (found) 
      return new BCSMappedTable(); 
else 
return tablist1;//or something else 
其他部分
-2

試試這個

public static BCSMappedTable GetMappedTable(string p_ListName) 
{ 
    List<BCSDataBase> ConnexionList = BCSManagement.GetAllDataBases(); 
    bool found = false; 
    foreach (BCSDataBase connexion in ConnexionList) 
    { 
     foreach (BCSMappedTable tabList in connexion.GetMappedTables()) 
     { 
      if (tabList.getListeName().Equals(p_ListName)) 
      { 
       found = true; 
       return tabList; 
      } 
     } 
    } 
    if (found) 
     { 
     return new BCSMappedTable(); 
     } 
    return found; 
} 
+2

'found'是一個bool ...你不能回報。 – Curt

+2

找到是一個bool,而不是BCSMappedTable。 –

0

在你的代碼有:

found = true; 
return tabList; 

沒有必要爲局部變量設置一個值,然後直接返回,因爲不會使用此變量。 return基本上用你正在返回的值(它應該與你的方法的類型相匹配)退出方法。

由於錯誤狀態,並非所有路徑都返回一個值。如果found==false將不會有返回值。

1
public static BCSMappedTable GetMappedTable(string p_ListName) 
    { 
     List<BCSDataBase> ConnexionList = BCSManagement.GetAllDataBases(); 
     bool found = false; 
     foreach (BCSDataBase connexion in ConnexionList) 
     { 
      foreach (BCSMappedTable tabList in connexion.GetMappedTables()) 
      { 
       if (tabList.getListeName().Equals(p_ListName)) 
       { 
        found = true; 
        return tabList; 
       } 
      } 
     } 
     if (!found) 
      return new BCSMappedTable(); 
    } 
相關問題