【问题标题】:vb.net Cannot convert Dictionary(Of String, List(Of String)) to Objectvb.net 无法将 Dictionary(Of String, List(Of String)) 转换为 Object
【发布时间】:2015-12-28 15:56:12
【问题描述】:

我在 vb.net 中有一个 Web 服务,它返回 json 格式的数据。其中一个数据项可以采用多种不同类型的值:BooleanStringDictionary(of String, String)Dictionary(Of String, Object) 后者是为了允许返回灵活的数据列表。然后,每个都在响应中指定了 itemType 和 DataType,因此第三方知道会发生什么。这工作得很好。

但是,我现在在尝试返回 Dictionary(Of String, Dictionary(Of String, List(Of String))) 时遇到以下错误:

Value of type 'System.Collections.Generic.Dictionary(Of String, System.Collections.Generic.Dictionary(Of String, System.Collections.Generic.List(Of String)))' cannot be converted to 'System.Collections.Generic.Dictionary(Of String, Object)'.

很可能会使用Dictionary(Of String, Dictionary(Of String, String)) 而不是Dictionary(Of String, Dictionary(Of String, List(Of String)))。我很困惑 - 我虽然几乎任何东西都可以转换为Object?为什么 Dictionary(Of String, String) 可以转换为 oject 而不是 Dictionary(Of String, List(Of String))

我可以通过以下方式绕过它:

Dim Bar As New Dictionary(Of String, Dictionary(Of String, List(Of String)))
' Add stuff to bar here

Dim Foo As New Dictionary(Of String, Object)
For Each Row As KeyValuePair(Of String, Dictionary(Of String, List(Of String))) In Bar
    Foo.Add(Row.Key, New Dictionary(Of String, Object))
    For Each Item As KeyValuePair(Of String, List(Of String)) In Row.Value
        Foo(Row.Key).add(Item.Key, Item.Value)
    Next
Next

但我不明白为什么我需要这样做。有什么我遗漏的东西可能会导致以后出现问题,谁能解释一下哪些类型的对象不能转换为Object

【问题讨论】:

    标签: vb.net casting type-conversion


    【解决方案1】:

    我认为您正在寻找的功能是协方差。 IDictionary(Of TKey, TValue) 不是协变的。这意味着Dictionary(Of String, String) 不能直接转换为不太具体的类型,例如IDictionary(Of String, Object)

    IEnumerable(Of T) 是协变的(从 .Net 4.0 开始),因此您可以将 List(Of String) 转换为 IEnumerable(Of Object)

    当然,像Dictionary(TKey, TValue) 这样的所有类最终都派生自 Object,所以你可以这样做:

    Dim myObject As New Dictionary(Of String, String)
    Dim myDictionary As New Dictionary(Of String, Object)
    myDictionary.Add("Test1", myObject)
    

    你也可以这样做:

    Dim myObject As New Dictionary(Of String, Dictionary(Of String, List(Of String)))
    Dim myDictionary As New Dictionary(Of String, Object)
    myDictionary.Add("Test2", myObject)
    

    但是,你不能做你在这里声称做过的事情:

    Dim myDictionary1 As New Dictionary(Of String, Dictionary(Of String, String))
    Dim myDictionary2 As IDictionary(Of String, Object) = myDictionary1
    

    myDictionary1 是一个对象,因此可以像这样将它添加到 myDictionary2(一旦 myDictionary2 被实例化):myDictionary2.Add("Test3", myDictionary1) 但它不能转换为类型 IDictionary(Of String, Object),因为 IDictionary(TKey, TValue) 不是协变的。

    请看https://stackoverflow.com/a/2149602/1887337 和 Eric Lippert 在这里解释了为什么字典是这样设计的:https://stackoverflow.com/a/5636770/1887337

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      • 2014-10-22
      • 2012-07-19
      • 1970-01-01
      相关资源
      最近更新 更多