【问题标题】:Show Key Value Pair Values of Dictionary on Text Writer在文本编写器上显示字典的键值对值
【发布时间】:2018-12-24 19:47:01
【问题描述】:

当我写入 CRM 的跟踪日志时,我正在跟踪以查看字典的值。

我看到以下内容:

键: System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Double] 价值: System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Double]

我看过以前的答案并说要使用:

myDictionary.Keys, myDictionary.Values

我做了如下:

tracer.Trace("Key: {0} Value: {1}", currentSiblingHours.Keys, currentSiblingHours.Values);

为什么我仍然看不到实际的键和值?

【问题讨论】:

  • 为什么是-1?这是一个完全有效的问题。

标签: c# dictionary key-value


【解决方案1】:

怎么样:

foreach(var keyValuePair in myDictionary)
       tracer.Trace("Key: {0} Value: {1}", keyValuePair.Key, keyValuePair.Value);

【讨论】:

  • 这是我一直在寻找的答案。 CRM 需要 ILMerge 才能使用 Newtonsoft.JSON 程序集。以前对我来说很痛苦。谢谢。
【解决方案2】:

Dictionary<TKey, TValue>Keys 属性返回一个KeyCollection,并且您的代码正在对该尚未实现的对象调用ToString(),因此为什么您在输出中有一个类型名称。您可以将字典序列化为 JSON:

tracer.Trace("Data: {0}", JsonConvert.SerializeObject(currentSiblingHours);

或者你可以使用string.Join:

tracer.Trace("Key: {0} Value: {1}", 
    string.Join(", ", currentSiblingHours.Keys), 
    string.Join(", ", currentSiblingHours.Values));

【讨论】:

    【解决方案3】:

    KeysValues 都是集合。默认的ToString() 将简单地返回它们的类型。如果您想在字符串中包含键和值或字典本身,您应该以某种方式对其进行序列化 - 最简单的方法是使用 Newtonsoft 库中的 JsonConvert.SerializeObject

    【讨论】:

      猜你喜欢
      • 2018-03-23
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 2017-11-07
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多