【发布时间】:2020-01-27 20:21:25
【问题描述】:
在 C# 中,我正在读取IDictionary<string, object> 类型的属性Config。我无法访问objectelements 中的信息。它应该是一个 JSON 字符串,但是它被包装为对象。
在 VisualStudio 的即时窗口中,输入 Config 输出:
Count = 1
[0]: {[items, Count = 3]}
深入研究项目:
var configItemsElement = Config["items"]
在即时窗口输出中输入configItemsElement:
Count = 3
[0]: {[1, {{ value = SeoChoiceInherit, sortOrder = 1 }}]}
[1]: {[2, {{ value = SeoChoiceYes, sortOrder = 2 }}]}
[2]: {[3, {{ value = SeoChoiceNo, sortOrder = 3 }}]}
输入configItemsElement.ToString() 会返回此类型信息:
System.Collections.Generic.Dictionary`2[System.String,<>f__AnonymousType7`2[System.String,System.Int32]]
据我所知。我无法访问configItemsElement 的元素。比如
configItemsElement[1]
结果为@987654333@
在 VisualStudio 的“Autos”窗口中,configItemsElement的信息是
configItemsElement
Value: Count = 3
Type: object {System.Collections.Generic.Dictionary<string, <>f__AnonymousType7<string, int>>}
type 信息是什么意思?它提示字典,但应用带有configItemsElement[1] 的键会导致上述错误。如何将此对象转换为我可以使用的类型?我尝试的任何演员都会导致错误。
编辑:
我无权访问提供 .Config 属性的代码,但我可以在 SQL 资源管理器中看到正在读入属性的数据。 SQL Explorer 显示了这些数据:
{"items":[{"id":1,"value":"SeoChoiceInherit"},{"id":2,"value":"SeoChoiceYes"},{"id":3,"value":"SeoChoiceNo"}]}
按照 symap 的回答中的建议,使 configItemsElement 动态化并访问 .value,例如:
dynamic configItemsElement = Config["Items"];
var myString =configItemsElement.value;
导致错误:
''object' does not contain a definition for 'value''
据我了解,因为 configItemsElement 应该包含字典。但是,如上所述,访问字典元素也不起作用。
【问题讨论】:
-
这可能有助于显示有错误的演员尝试
-
请分享它是如何在代码中声明的
-
似乎
configItemsElement是一个字典,其中string是键,值是int类型。你能告诉我们结构吗configItemsElement -
我无法访问提供
IDictionary<string, object>类型的.Config 属性的代码。但是我可以在 SQL 资源管理器中看到似乎读入此属性的数据: {"items":[{"id":1,"value":"SeoChoiceInherit"},{"id":2,"value" :"SeoChoiceYes"},{"id":3,value":"#SeoChoiceNo"}]} -
@Attersson:例如
configItemsElement as string给出null。我还定义了一些类来镜像包含的类型并明确地转换为此,我得到'指定的转换无效`
标签: c#