vb.net - 检查 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)
是一个结构(结构),它具有您可以比较的默认值。
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
推荐阅读
- php - 将多个图像上传到 PHP MySQL 中的特定数据库列
- python - 如何在 python Dash 中包含 TradingVue 图表
- reactjs - 在 Next.js 应用程序中使用 React 上下文时将数据从一个状态对象传输到另一个状态对象
- database - Spotify 使用什么样的数据结构来保存和搜索音乐?
- javascript - Gatsby setHeadComponents 设置异步标签
- powershell - PowerShell - 在远程计算机屏幕上显示消息
- excel - 具有最高值的变量
- node.js - 如何使用 Node JS (Express) 在 s3 存储桶中一次上传多个图像
- html - 即使按下一个按钮,也会显示另一个项目。jQuery
- javascript - JS SSE 回调不适用于 EventListener