检查 VB.NET 中值类型的空值
Check for null value for value types in VB.NET
我有一个 KeyValuePair(Of TKey,TValue)
,我想检查它是否为空:
Dim dictionary = new Dictionary(Of Tkey,TValue)
Dim keyValuePair = dictionary.FirstOrDefault(Function(item) item.Key = *someValue*)
If keyValuePair isNot Nothing Then 'not valid because keyValuePair is a value type
....
End If
If keyValuePair <> Nothing Then 'not valid because operator <> does not defined for KeyValuePair(of TKey,TValue)
...
End If
如何检查 keyValuePair
是否为空?
KeyValuePair(Of TKey, TValue)
是一个结构体(Structure),它有默认值,你可以比较它。
Dim dictionary As New Dictionary(Of Integer, string)
Dim keyValuePair = dictionary.FirstOrDefault(Function(item) item.Key = 2)
Dim defaultValue AS KeyValuePair(Of Integer, string) = Nothing
If keyValuePair.Equals(defaultValue) Then
' Not found
Else
' Found
End If
Nothing
表示对应类型的默认值。
但是因为您正在 Dictionary
搜索密钥,所以您可以使用 TryGetValue
代替
Dim dictionary As New Dictionary(Of Integer, string)
Dim value As String
If dictionary.TryGetValue(2, value) Then
' Found
Else
' Not found
End If
我有一个 KeyValuePair(Of TKey,TValue)
,我想检查它是否为空:
Dim dictionary = new Dictionary(Of Tkey,TValue)
Dim keyValuePair = dictionary.FirstOrDefault(Function(item) item.Key = *someValue*)
If keyValuePair isNot Nothing Then 'not valid because keyValuePair is a value type
....
End If
If keyValuePair <> Nothing Then 'not valid because operator <> does not defined for KeyValuePair(of TKey,TValue)
...
End If
如何检查 keyValuePair
是否为空?
KeyValuePair(Of TKey, TValue)
是一个结构体(Structure),它有默认值,你可以比较它。
Dim dictionary As New Dictionary(Of Integer, string)
Dim keyValuePair = dictionary.FirstOrDefault(Function(item) item.Key = 2)
Dim defaultValue AS KeyValuePair(Of Integer, string) = Nothing
If keyValuePair.Equals(defaultValue) Then
' Not found
Else
' Found
End If
Nothing
表示对应类型的默认值。
但是因为您正在 Dictionary
搜索密钥,所以您可以使用 TryGetValue
代替
Dim dictionary As New Dictionary(Of Integer, string)
Dim value As String
If dictionary.TryGetValue(2, value) Then
' Found
Else
' Not found
End If