Domanda

I have a function which has a selectedID parameter of type "object".

If my parameter is the default for the underlying type: i.e. Integer default is zero, I want some action to take place.

Without "Strict On", I can use:

If selectedID = Nothing Then
    'Do Something
End If

Do I have to do something like:

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

Or is there a simpler method that I'm missing?

È stato utile?

Soluzione

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

Altri suggerimenti

You can also use a nullable type for this.

Dim selectedID As Integer? = nothing

...

if selectedID isnot nothing then

    dim value as integer = selectedID.value
    ...

end if

Another way you can check the nullable type has been assigned a value.

if selectedID.hasValue = true then

   dim value as integer = selectedID.value
   ...

end if
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top