2013-05-09 69 views
2

可以說我有值「一,二,三」更好地使用SelectedIndex或SelectedItem的組合框?

一般來說一個ComboBox,基於該ComboBox選擇有條件的事件進行測試時,這將是更好的參考ComboBox.SelectedItem或ComboBox .SelectedIndex?

If (ComboBox.SelectedItem = "One") 

If (ComboBox.SelectedIndex = 0) 

抑或既沒有比其他的優勢?

+1

你認爲什麼更具可讀性? – 2013-05-09 20:52:10

+0

它只取決於你和你的團隊決定更易讀和可維護。 – Oded 2013-05-09 20:52:23

+0

好吧,我只是想知道如果處理明智的比其他處理更好 – 2013-05-09 20:54:16

回答

5

我發現SelectedIndex更容易使用,因爲你可以在一個數字上工作,當沒有選擇時你不必處理空。 SelectedItem可以爲null,並且在嘗試訪問該屬性時應該記住這一點。

通常的SelectedItem和SelectedIndex的是使用SelectedIndexChanged事件內,很容易忘記沒什麼可能性

Dim curValue = Combo.SelectedItem.ToString() ' <- Possible NullReferenceException' 
    ..... 

但是,如果我們只是在談論比較則不存在SelectedIndex的一個非常小的優勢,因爲有沒有加載和測試一個字符串。

ComboBox b = new ComboBox(); 
if(b.SelectedItem == "One") 
    Console.WriteLine("OK"); 
if(b.SelectedIndex == 0) 
    Console.WriteLine("OK"); 

IL代碼

IL_0000: newobj  System.Windows.Forms.ComboBox..ctor 
IL_0005: stloc.0  // b 
IL_0006: ldloc.0  // b 
IL_0007: callvirt System.Windows.Forms.ComboBox.get_SelectedItem 
IL_000C: ldstr  "One" 
IL_0011: bne.un.s IL_001D 
IL_0013: ldstr  "OK" 
IL_0018: call  System.Console.WriteLine 
IL_001D: ldloc.0  // b 
IL_001E: callvirt System.Windows.Forms.ListControl.get_SelectedIndex 
IL_0023: brtrue.s IL_002F 
IL_0025: ldstr  "OK" 
IL_002A: call  System.Console.WriteLine 

但我們在微優化的境界,正如一個評論說,用的是你更具可讀性。

+0

爲什麼你需要檢查'Nothing'? – 2013-05-09 20:58:54

+1

通常SelectedItem用於SelectedIndexChanged事件中,您應該記住它可以爲null以避免NullReferenceExceptio。我同意在上面的例子中並不是真的需要 – Steve 2013-05-09 21:02:49

2

SelectedIndex保證是唯一的,SelectedItem不是

相關問題