使用单个条件检查Class是否为Nothing,或者Structure是否为默认值

时间:2012-11-21 13:40:17

标签: .net vb.net reference null default-value

我编写了自己的方法,用于以编程方式选择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,但我知道必须有更好的方法。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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