vb.net 将 SelectedIndex 或 SelectedItem 用于 ComboBox 更好吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16470890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Better to use SelectedIndex or SelectedItem for ComboBox?
提问by Stas Bukhtiyarov
Lets say I have a ComboBox
with the values "One, Two, Three"
假设我有一个ComboBox
值“一,二,三”
As a general rule, when testing for conditional events based on the ComboBox
selection, would it be better to reference the ComboBox.SelectedItem or ComboBox.SelectedIndex?
作为一般规则,在测试基于ComboBox
选择的条件事件时,引用 ComboBox.SelectedItem 或 ComboBox.SelectedIndex 会更好吗?
If (ComboBox.SelectedItem = "One")
or
或者
If (ComboBox.SelectedIndex = 0)
Or does neither have an advantage over the other?
或者两者都没有比另一个优势?
回答by Steve
I find SelectedIndex
easier to use because you can work on a number and when there is no selection you don't have to handle the null. SelectedItem could be null and you should remember this when trying to access that property.
我发现SelectedIndex
更容易使用,因为您可以处理一个数字,并且当没有选择时,您不必处理空值。SelectedItem 可能为 null,您应该在尝试访问该属性时记住这一点。
Usually SelectedItem and SelectedIndex are used inside a SelectedIndexChanged event and it easy to forget the Nothing possibility
通常 SelectedItem 和 SelectedIndex 在 SelectedIndexChanged 事件中使用,很容易忘记 Nothing 可能性
Dim curValue = Combo.SelectedItem.ToString() ' <- Possible NullReferenceException'
.....
However, if we are just talking about comparison then there is a very small advantage for SelectedIndex because there is no loading and testing of a string.
然而,如果我们只是在谈论比较,那么 SelectedIndex 有一个非常小的优势,因为没有加载和测试字符串。
ComboBox b = new ComboBox();
if(b.SelectedItem == "One")
Console.WriteLine("OK");
if(b.SelectedIndex == 0)
Console.WriteLine("OK");
IL Code
代码
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
But we are in the realm of micro-optimizations and, as said in a comment, use what is more readable for you.
但是我们处于微优化领域,正如评论中所说,使用对您来说更具可读性的内容。
回答by mfeingold
SelectedIndex is guaranteed to be unique, SelectedItem is not
SelectedIndex 保证是唯一的,SelectedItem 不是