2011-06-07 116 views
0

我需要編寫一個條件語句來檢查L標籤是否存在。C#中的嵌套if語句

  • 如果L選項卡不存在,它會打印「L不存在」。
  • 如果選擇L,它將打印「L存在」,並檢查是否S,C和K標籤存在:
    • 若S存在,它會打印出「S是目前」其他「 S是不存在的。
    • 如果C是目前它就會打印 「C存在」,否則 「C不存在」,
    • ...和同爲K.

我寫下如下代碼,但由於某種原因,代碼對我來說看起來不太好,任何想法都可以受到高度讚賞。謝謝!

if (Sel.IsElementPresent(arrObj1[4])) 
{ 
    Lib.WriteDebugLogs("Test 1: General", "NORMAL", "L tab present in home page"); 
    Sel.Click(arrObj1[4]); 
    if (Sel.IsElementPresent(arrObj1[5])) 
    { 
     Lib.WriteDebugLogs("Test 1: General", "NORMAL", "S tab present under L tab."); 
    } 

    if (Sel.IsElementPresent(arrObj1[6])) 
    { 
     Lib.WriteDebugLogs("Test 1: General", "NORMAL", "C tab present under L tab."); 
    } 

    if (Sel.IsElementPresent(arrObj1[7])) 
    { 
     Lib.WriteDebugLogs("Test 1: General", "NORMAL", "K tab present under L tab."); 
    } 


} 
else 
{ 
    s = "'L' tab is not displayed in the home page."; 
    arrTestResults[6] = arrTestResults[7] = s; 
    Lib.WriteDebugLogs("Test 1: General", "****ERROR****", "Could noT find the L tab"); 
} 
+0

使代碼更具可讀性的一個非常簡單的事情是用一個自我註釋標識符(例如'tabK'等變量)替換'arrObj1 [x]' - 可以說這樣做不會使用'arrObj1'數組根本... – 2011-06-07 22:00:14

回答

3

你應該幾乎從來不會在數組中引用數值,你所知道的「魔術常數」指的是特定的元素。所以我要去承擔這個方法被調用之前的某個地方,有人做了這樣的事情:

var tabs = new[] { 
    new Tab{Name = "L", ParentName= "home page", Identifier = arrObj1[4], 
    // and so on for the tabs you care about. 
    }; 

這樣一來,你的方法的第一部分可以與僅涉及顯示方法代替關於被顯示的信息標籤:

public void LogDisplayedTabs(IEnumerable<Tab> tabs) 
{ 
    for(var tab in tabs) 
    { 
     if (Sel.IsElementPresent(tab.Identifier)) 
     { 
      Lib.WriteDebugLogs("Test 1: General", "NORMAL", 
       string.Format("{0} tab present under {1} tab.", tab.Name, tab.ParentName)); 
     } 
    } 
} 

我沒有現在的時間解決方法的休息,但這個模式應該可以幫助你找出如何解決其餘部分。