代码之家  ›  专栏  ›  技术社区  ›  Mark

asp.net vb.net人物类与词典

  •  0
  • Mark  · 技术社区  · 16 年前

    这个问题与此有关 Multidimensional Associative Array in VB.NET

    得到以下错误。

    系统。ArgumentException:已添加具有相同键的项。

    Dim AdInsured As New Dictionary(Of String, Person)()
    
        Do While dbread.HasRows
            AdInsured.Add(dbread.Item("FullName"), New Person(dbread.Item("FullName"), GetAge(dbread.Item("DateOfBirth"))))
        Loop
    
    2 回复  |  直到 9 年前
        1
  •  2
  •   Fredrik Mörk    16 年前

    字典中的键必须是唯一的。如果你有一个键为“John”的项目,并尝试用相同的键添加另一个项目,你会得到这个异常。您需要确保字典中的每个项目都有一个唯一的密钥。您可以检查字典中是否已使用密钥:

    If AdInsured.ContainsKey(dbread.Item("FullName")) Then
        ' The dictionary already has an item with this key '
    Else
        ' You can safely add the new item to the list '
        AdInsured.Add(dbread.Item("FullName"), New Person(dbread.Item("FullName"), GetAge(dbread.Item("DateOfBirth"))))
    End If
    
        2
  •  0
  •   Peter Knowles Peter Knowles    16 年前

    添加到字典时,添加的第一个项将是键(在本例中为字符串)-这在字典中必须是唯一的,否则将抛出此错误。

    我也会使用这个字典声明,否则你会得到一个字典数组

    将a定为新的Generic。字典(字符串,字符串) 已同意2.加上(“弗雷德”、“弗雷德”) 已同意2.加上(“弗雷德”、“弗雷德”)

    将a定为新的Generic。字典(字符串,字符串) 已同意2.添加(“伯特”、“弗雷德”) 已同意2.加上(“弗雷德”、“弗雷德”)