2012-09-26 39 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(); 
    } 
相关问题