如何制作通用代码将任何 IEnumerable 转储到调试器并单独处理 KeyValuePair

问题描述 投票:0回答:1

我想将任何集合的内容写入调试器,无论是字典还是字典。但对于Dictionnary,我想分别识别Key和Value,而不必知道键或值的类型是什么。

在下面的代码中,我可以将“KeyValuePair”替换为有效的内容以使代码按预期工作吗?

    [Conditional("DEBUG")]
    public static void Dump<T>(this IEnumerable<T> enumerable)
    {
        Debug.WriteLine($"START: Enumeration of type {typeof(T).Name}");
        foreach (T item in enumerable)
        {
            if (item is KeyValuePair kvp)
            {
                Debug.WriteLine($"Key: {kvp.Key,-20}, Value: {kvp.Value}");
            }
            else
            {
                Debug.Print(item?.ToString() ?? "<empty string>");
            }
        }
        Debug.WriteLine($"END  : Enumeration of type {typeof(T).Name}");
    }
c# templates generics ienumerable debug-window
1个回答
0
投票

对于您所询问的确切场景,最简单的方法是编写不同的

Dump
重载来处理任何
IReadOnlyDictionary<K, V>
,因此枚举项类型将为
KeyValuePair<K, V>

但是当您尝试处理更多情况时,您可能需要考虑递归结构,例如字典列表的字典,在这种情况下,您的

Dump
方法将需要递归并能够接受任何
object
,因此它可以在运行时分派到正确的格式化代码,而完全不依赖于已知的类型编译时间。但这是另一个问题了!

© www.soinside.com 2019 - 2024. All rights reserved.