gpt4 book ai didi

vb.net - 对于 ComboBox 使用 SelectedIndex 或 SelectedItem 更好?

转载 作者:行者123 更新时间:2023-12-03 00:35:26 25 4
gpt4 key购买 nike

假设我有一个 ComboBox,其值为“一、二、三”

作为一般规则,当基于 ComboBox 选择测试条件事件时,引用 ComboBox.SelectedItem 或 ComboBox.SelectedIndex 会更好吗?

If (ComboBox.SelectedItem = "One") 

If (ComboBox.SelectedIndex = 0)

或者两者都没有优于对方的优势?

最佳答案

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

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

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

但是我们处于微优化领域,正如评论中所说,使用对您来说更易读的内容。

关于vb.net - 对于 ComboBox 使用 SelectedIndex 或 SelectedItem 更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16470890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com