You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.NET中使用多键字典获取并更新多组值

结构体作为键时,Dictionary的检索与更新方法

你已经基于自定义结构体创建了Dictionary(Of TestKeys, TestValues)集合,以下是针对指定键的检索和更新操作方法,以及关键注意事项:

一、检索对应值

1. 直接使用索引器(键存在时适用)

先构造匹配的TestKeys实例,通过字典索引器直接获取值:

' 构造目标键
Dim targetKey As New TestKeys() With {.Key1 = "xx", .Key2 = "yy"}
' 获取对应值
Dim targetValue As TestValues = Test(targetKey)

注意:如果字典中不存在该键,此操作会抛出KeyNotFoundException,不确定键是否存在时不建议使用。

2. 用TryGetValue安全检索(推荐不确定键存在性时使用)

此方法不会抛出异常,返回布尔值标识是否找到键:

Dim targetKey As New TestKeys() With {.Key1 = "xx", .Key2 = "yy"}
Dim targetValue As TestValues

If Test.TryGetValue(targetKey, targetValue) Then
    ' 找到键,处理获取到的targetValue
    Console.WriteLine($"Value1: {targetValue.Value1}, Value2: {targetValue.Value2}")
Else
    ' 未找到键的处理逻辑
    Console.WriteLine("指定的键不存在于字典中")
End If

二、更新对应值

1. 键已存在时更新

由于TestValues是值类型,不能直接修改结构体的单个字段(如Test(targetKey).Value1 = True会报错),需先取出整个结构体修改后再存回:

Dim targetKey As New TestKeys() With {.Key1 = "xx", .Key2 = "yy"}
' 方式1:直接替换整个TestValues实例
Test(targetKey) = New TestValues() With {.Value1 = True, .Value2 = 1.5F, .Value3 = 2.0F, .Value4 = 3.0F, .Value5 = 4.0F}

' 方式2:修改结构体单个字段
Dim currentValue As TestValues = Test(targetKey)
currentValue.Value1 = True
currentValue.Value2 = 1.5F
Test(targetKey) = currentValue

2. 键不存在时自动添加/更新

如果不确定键是否存在,直接使用索引器赋值即可——键存在则更新,不存在则添加新的键值对:

Dim targetKey As New TestKeys() With {.Key1 = "newKey1", .Key2 = "newKey2"}
Test(targetKey) = New TestValues() With {.Value1 = True, .Value2 = 5.0F}

关键注意事项:结构体作为字典键的要求

字典依赖键的Equals和GetHashCode方法判断键的唯一性。虽然结构体默认会基于字段生成这两个方法,但为了避免潜在的匹配错误(如内存布局影响),建议手动重写这两个方法:

Structure TestKeys
    Public Key1 As String
    Public Key2 As String

    Public Overrides Function Equals(obj As Object) As Boolean
        If obj Is Nothing OrElse Not TypeOf obj Is TestKeys Then
            Return False
        End If
        Dim otherKey As TestKeys = DirectCast(obj, TestKeys)
        Return Key1 = otherKey.Key1 AndAlso Key2 = otherKey.Key2
    End Function

    Public Overrides Function GetHashCode() As Integer
        ' 基于两个键字段生成哈希码,可根据需求调整算法
        Return HashCode.Combine(Key1, Key2)
    End Function
End Structure

内容的提问来源于stack exchange,提问作者sp64

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 22:46:01