首页 > 解决方案 > 检查 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为空?

标签: vb.netkey-valuevalue-typereference-typenothing

解决方案


KeyValuePair(Of TKey, TValue)是一个结构(结构),它具有您可以比较的默认值。

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

推荐阅读