2013-08-16 33 views
1

試圖爲我的受保護字符串函數中的每個循環添加一個,但不斷收到錯誤:「並非所有代碼路徑都返回一個值」。請幫忙。對於受保護字符串函數中的每個循環

protected string GetAmountStyle() 
{ 
    { 
    foreach (LFConnection ProdCurrConn in AllConn) 
    { 
     if (Login.Contains(ProdCurrConn.UserName) == false) 
     if ((Request.Browser.Browser.Contains("IE") == true)) 
     { 
      //th1.Attributes.Add("style", "padding-right: 5px;"); 
      //return "padding-right: 1px;"; 
      return "background-color: #FFFF66;"; 
     } 
     else 
     { 
      //th1.Attributes.Add("style", "padding-right: 5px;"); 
      return "background-color: #FFFF66;"; 
     } 
     else 
     { 
     //th1.Attributes.Add("style", "padding-right: 5px;"); 
     return string.Empty; 
     } 
    } 
+0

提示:如果AllConn爲空會發生什麼? – briantyler

回答

5

問題是,如果AllConn爲空,您的方法將永遠不會返回一個值,因爲您在foreach之後沒有任何回報。

話雖這麼說,你的循環,現在也只能檢查AllConn的第一個值,因爲foreach中的每個路徑將返回一定的價值,所以這是不可能的檢查第二個「康涅狄格州」元素。

我懷疑你真的是更多的東西一樣後:喜歡可能性是存在的「AllConn」可能是空

protected string GetAmountStyle() 
{ 
    if (AllConn.Any(ProdCurrConn => !Login.Contains(ProdCurrConn.UserName)) 
    { 
     if ((Request.Browser.Browser.Contains("IE") == true)) 
     { 
      //th1.Attributes.Add("style", "padding-right: 5px;"); 
      //return "padding-right: 1px;"; 
      return "background-color: #FFFF66;"; 
     } 
     else 
     { 
      //th1.Attributes.Add("style", "padding-right: 5px;"); 
      return "background-color: #FFFF66;"; 
     } 
    } 

    return string.Empty; 
} 
0

如果AllConn是空集有什麼返回路徑?

0

提示:如果AllConn爲空,您的代碼返回什麼?

foreach之外添加默認路徑;任何的:

return ""; 

return null; 

throw new InvalidOperationException("AllConn cannot be empty"); 

(或任何其他你想要的,真的)

注:這可能是因爲你知道AllConn是從來沒有空,由於一些規則,你知道;然而 - 編譯器不相信你對此; foreach的邏輯表示不能保證永遠輸入內部語句。

0

聲音對我來說,這樣的循環的條件永遠不會得到執行,因此函數沒有按不會返回一個字符串。我將包含一個返回語句,用於循環從不執行的情況。

0

如果您是AllConn收藏品中沒有任何物品,則不會返回任何物品。試試這個:

protected string GetAmountStyle() 
{ 
    foreach (LFConnection ProdCurrConn in AllConn) 
    { 

     if (Login.Contains(ProdCurrConn.UserName) == false) 
     { 
      if ((Request.Browser.Browser.Contains("IE") == true)) 
      { 
       //th1.Attributes.Add("style", "padding-right: 5px;"); 
       //return "padding-right: 1px;"; 
       return "background-color: #FFFF66;"; 
      } 
      else 
      { 
       //th1.Attributes.Add("style", "padding-right: 5px;"); 
       return "background-color: #FFFF66;"; 
      } 
     } 
     else 
     { 
      //th1.Attributes.Add("style", "padding-right: 5px;"); 
      return string.Empty; 
     } 
    } 

    return string.Empty; 
}