在文本编写器上显示字典的键值对值

Show Key Value Pair Values of Dictionary on Text Writer

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

我看到以下内容:

Key: System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Double] Value: System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Double]

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

myDictionary.Keys, myDictionary.Values

我做了如下:

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

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

KeysValues都是合集。默认 ToString() 将只是 return 他们的类型。如果你想在字符串中包含键和值,或者字典本身,你应该以某种方式序列化它——最简单的方法是使用 Newtonsoft 库中的 JsonConvert.SerializeObject

Keys property of a Dictionary<TKey, TValue> returns a 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));

怎么样:

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