1

我已经编写了自己的方法来以编程方式选择 ComboBox 中的项目:

Function SelectItem(ByVal item As Object, ByVal comboBox As ComboBox) As Boolean
  If Not comboBox.Items.Contains(item) Then
    comboBox.Items.Add(item)
  End If

  comboBox.SelectedItem = item

  Return True
End Function

"item" 参数可以是任意Class的,例如字符串,但也可以是 (custom) Structure

当参数为Nothing(或默认结构值)时,此方法应返回False. 我如何达到这个条件?

' This will not work, because "=" can't be used with classes
If item = Nothing Then Return False

' Won't work either, because "Is" is always False with structures
If item Is Nothing Then Return False

' Obviously this would never work
If item.Equals(Nothing) Then Return False

' Tried this too, but no luck :(
If Nothing.Equals(item) Then Return False

我应该如何处理这种情况?我可以使用Try ... Catch,但我知道必须有更好的方法。

4

2 回答 2

3

这个函数可以解决问题:

Public Function IsNullOrDefaultValue(item As Object) As Boolean
    Return item Is Nothing OrElse (item.GetType.IsValueType Andalso item = Nothing)
End Function

通过传递变量测试结果:

Dim emptyValue As Integer = 0          ==> True
Dim emptyDate As DateTime = Nothing    ==> True
Dim emptyClass As String = Nothing     ==> True
Dim emptyStringValue As String = ""    ==> False
Dim stringValue As String = "aa"       ==> False
Dim intValue As Integer = 1            ==> False
于 2012-11-21T14:38:13.337 回答
0

我不太确定您希望在哪些条件下返回 True/False,但此代码显示了如何检查类型并将其与特定值进行比较。这样,如果类型错误,您就不会尝试将其与值进行比较。

If (TypeOf myVar is MyClass andalso myVar isnot nothing) _
    OrElse TypeOf myVar is MyStructure AndAlso myVar = MyStructure.DefaultValue) Then
    ...
End If
于 2012-11-21T14:45:25.507 回答