Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 对于组合框,最好使用SelectedIndex或SelectedItem?_Vb.net - Fatal编程技术网

Vb.net 对于组合框,最好使用SelectedIndex或SelectedItem?

Vb.net 对于组合框,最好使用SelectedIndex或SelectedItem?,vb.net,Vb.net,假设我有一个值为“一、二、三”的组合框 作为一般规则,在基于ComboBox选择测试条件事件时,最好是引用ComboBox.SelectedItem还是ComboBox.SelectedIndex If (ComboBox.SelectedItem = "One") 或 或者两者都没有优势?我发现SelectedIndex更容易使用,因为你可以处理一个数字,当没有选择时,你不必处理空值。SelectedItem可以为null,您在尝试访问该属性时应该记住这一点 通常,SelectedItem

假设我有一个值为“一、二、三”的组合框

作为一般规则,在基于
ComboBox
选择测试条件事件时,最好是引用ComboBox.SelectedItem还是ComboBox.SelectedIndex

If (ComboBox.SelectedItem = "One") 


或者两者都没有优势?

我发现
SelectedIndex
更容易使用,因为你可以处理一个数字,当没有选择时,你不必处理空值。SelectedItem可以为null,您在尝试访问该属性时应该记住这一点

通常,SelectedItem和SelectedIndex在SelectedIndexChanged事件中使用,很容易忘记Nothing的可能性

Dim curValue = Combo.SelectedItem.ToString() ' <- Possible NullReferenceException'
  .....
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

但是我们在微优化领域,正如一篇评论中所说,使用对您来说更可读的索引。

SelectedIndex保证是唯一的,SelectedItem不是您认为更可读的索引?它只取决于您和您的团队决定什么更可读和可维护。好的,我只是想知道处理智能的一个是否比另一个更好——问题1“==”不是相等运算符吗?我想你在这里做作业。不是在vb.net 2005中,但是如果你想的话,就把它当作伪代码处理。你为什么需要检查
什么都没有
?通常SelectedItem在SelectedIndexChanged事件中使用,你应该记住它可以为null以避免NullReferenceException。我同意,在上面的例子中,并不是真的需要
ComboBox b = new ComboBox();
if(b.SelectedItem == "One")
  Console.WriteLine("OK");
if(b.SelectedIndex == 0)
  Console.WriteLine("OK");
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