2015-09-30 132 views
2

我在vb.net中有一個web服務,它返回json格式的數據。其中一個數據項可以採用許多不同類型的值:BooleanStringDictionary(of String, String)Dictionary(Of String, Object)後者允許返回靈活的數據列表。然後在響應中分別指定一個itemType和DataType,以便三方知道期望什麼。這工作得很好。vb.net無法將Dictionary(Of String,List(Of String))轉換爲Object

不過,我現在收到以下錯誤試圖返回一個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

回答

2

我認爲你正在尋找的功能是協方差。 IDictionary(Of TKey, TValue)不是共同變體。這意味着Dictionary(Of String, String)不能直接轉換爲像IDictionary(Of String, Object)這樣的不太具體的類型。

IEnumerable(Of T)是co-variant但是(如.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 和埃裏克利珀的解釋,此間正是爲什麼字典是這樣設計的:https://stackoverflow.com/a/5636770/1887337

相關問題