【问题标题】:Reading values inside Dictionary<string, object>读取 Dictionary<string, object> 中的值
【发布时间】:2019-10-12 09:41:18
【问题描述】:

我正在使用编辑器数据表并将数据从编辑器返回到控制器,并尝试从所谓的Dictionary&lt;string,object&gt; 中读取值。任何人都可以建议这是如何完成的。我读到 Dictionary 需要进行 Json 反序列化,但不太确定它是如何完成的。我包括一张我试图阅读的价值观的图片。谢谢enter image description here

我在控制器中读取了通过 e.Values 返回的数据:

editor.PostCreate += (sender, e) => t = Task.Run(() => Add(intContTpe, lngContIdx, e.Values));
internal static void Add(int intContTpe, long lngContIdx, object objPCEAValues)
{
    Dictionary<string, object> dicVoDaCDRFormats = new Dictionary<string, object>();
    if (!dicPCEAValues.ContainsKey("CustomerVoiceCLICDRFormats.0"))
    {
        dicVoDaCDRFormats = ((Dictionary<string, object>)dicPCEAValues["CustomerVoiceCLICDRFormats"]);

        PrintToOutput("", ((Dictionary<string, object>)dicPCEAValues["CustomerVoiceCLICDRFormats"])["0"]);
    }
}

【问题讨论】:

  • 您已经有一本包含所需值的字典。为什么要反序列化?如果您希望对象成为特定类型,只需转换它们即可。
  • foreach (KeyValuePair items in dicVoDaCDRFormats) { PrintToOutput("", items.Value);如果我尝试从 dicVoDaCDRFormats 迭代键值对,我得到的不是图片中的值,而是“System.Collections.Generic.Dictionary`2[System.String,System.Object]”

标签: c# model-view-controller datatables


【解决方案1】:

dicVoDaCDRFormats 中的每个值都是它自己的字典。您还需要打开这些字典。

检查这是否为您提供了预期的结果。

foreach (KeyValuePair<string, object> items in dicVoDaCDRFormats) 
{
    if (items.Value is Dictionary<string, object> innerDict)
        foreach (var item in innerDict)
            PrintToOutput("", items.Value); 
}

这种使用object 类型的工作是不安全的。您可以使用 isas 关键字为其他部分添加类型检查以确保安全。但这取决于您正在处理的案例。

【讨论】:

  • 您可以标记答案。投赞成票也会让我高兴:)
猜你喜欢
  • 1970-01-01
  • 2021-07-18
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 2023-04-03
  • 2014-10-22
  • 2012-05-13
相关资源
最近更新 更多