检查VB.NET中的值类型是否为null值



我有一个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

最新更新