vb.net无法将Dictionary(Of String,List(Of String))转换为Object

时间:2015-09-30 18:33:31

标签: vb.net casting type-conversion

我在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)可以转换为对象而不是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吗?

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找的功能是协方差。 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)类型,因为{{1} }不是共变体。

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