【发布时间】:2015-12-28 15:56:12
【问题描述】:
我在 vb.net 中有一个 Web 服务,它返回 json 格式的数据。其中一个数据项可以采用多种不同类型的值:Boolean、String、Dictionary(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