使用单个条件检查“类”是否为“无”或“结构”是默认值



我编写了自己的方法,用于以编程方式在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,如字符串,但它也可以是(自定义)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,但我知道一定有更好的方法。

这个函数可以解决问题:

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

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

If (TypeOf myVar is MyClass andalso myVar isnot nothing) _
    OrElse TypeOf myVar is MyStructure AndAlso myVar = MyStructure.DefaultValue) Then
    ...
End If

相关内容

  • 没有找到相关文章

最新更新