1

我有一个函数,它有一个“object”类型的 selectedID 参数。

如果我的参数是基础类型的默认值:即整数默认值为零,我希望执行一些操作。

没有“严格”,我可以使用:

If selectedID = Nothing Then
    'Do Something
End If

我是否必须做类似的事情:

If (TypeOf selectedID Is Integer AndAlso selectedID.Equals(0)) _
OrElse (TypeOf selectedID Is String AndAlso selectedID.Equals(Nothing)) _
OrElse .. other types go here .. Then
    'Do something
End If

还是我缺少一种更简单的方法?

4

2 回答 2

0

I eventually implemented Neolisk's suggestion, which had the advantage of being short, all-encompassing and very re-usable:

Public Function IsDefaultObject(obj As Object) As Boolean
    Return obj.Equals(GetDefaultValue(obj.GetType()))
End Function

Public Function GetDefaultValue(t As Type) As Object
    If (t.IsValueType) Then Return Activator.CreateInstance(t)
    Return Nothing
End Function

I originally went with the solution of creating a function IsDefaultObject(obj) which tells me if an object has had a default value assigned. I planned to add to it as more types got noticed.

Private Function IsDefaultObject(obj As Object) As Boolean
    If obj Is Nothing Then Return True
    If String.IsNullOrEmpty(obj.ToString()) Then Return True
    If obj.Equals(0) Then Return True
    If obj.Equals(New Date()) Then Return True
    Return False
End Function

Of course, I could have used the solution in Hans Passant's comment:

Private Function IsDefaultObject(obj As Object) As Boolean
    Return Microsoft.VisualBasic.CompilerServices.Operators.
        ConditionalCompareObjectEqual(obj, Nothing, False)
End Function
于 2013-02-26T12:28:39.830 回答
-1

您也可以为此使用可为空的类型。

Dim selectedID As Integer? = nothing

...

if selectedID isnot nothing then

    dim value as integer = selectedID.value
    ...

end if

另一种检查可空类型是否已被赋值的方法。

if selectedID.hasValue = true then

   dim value as integer = selectedID.value
   ...

end if
于 2013-02-26T13:21:05.373 回答