首页 > 解决方案 > 仅在 VisualStudio 的调试器中按键对字典进行排序

问题描述

我在我的应用程序中使用基于 Dictionary 的对象。调试时(并且仅当我检查字典时)我想查看字典的内容,但按键排序。

我知道我可以使用 SortedDictionary 而不是 Dictionary 但与 Dictionary 相比性能较差,我不想影响性能。

我也不想有“#if debug”条件。

可能吗 ?

标签: c#dictionarydebugging

解决方案


你可以在你的类上指定一个DebuggerTypeProxyAttribute(),当你调试时/如果你使用它。该代理必须为您对数据进行排序。

文章:使用调试器显示属性增强调试

使用 a 的(无意义的)孩子的示例Dictionary<string,int>

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

internal class Program
{
    /// <summary>
    /// Derives from a Dictionary that is not sorted
    /// </summary>
    [DebuggerTypeProxy(typeof(DictDebugView))]
    public class MyDictionary : Dictionary<string, int>
    {
        /// <summary>
        /// Prepares unsorted dummy data
        /// </summary>
        public void PopulateDemoData()
        {
            foreach (char t in "GERZWIQSFHIWE")
               this[new string(t, t / 10)] = t;
        }

        /// <summary>
        /// Is used as proxy for display
        /// </summary>
        internal class DictDebugView
        {
            private readonly SortedDictionary<string, int> sorted;
            public DictDebugView(Dictionary<string, int> data)
                => sorted = new SortedDictionary<string, int>(data);

            /// <summary>
            /// Create the displayed KeyValuePairs
            /// </summary>
            [DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
            public IList<KeyValuePair<string,int>> Keys
            {
                get => sorted.Select(kvp => kvp).ToList();
            }
        }
    } 

    public static MyDictionary MyProp { get; } = new MyDictionary();

    public static void Main(string[] args)
    {
        var md = new MyDictionary();
        md.PopulateDemoData();

        var k = new Dictionary<string,int>(md); 

        Console.ReadLine();
    } 
}

如果您放置断点并进行调试,您将获得带有内部 DebuggerTypeProxy 的类的排序输出:

使用 DebuggerTypeProxy

以及不使用任何代理来显示其数据的“普通”字典的未排序输出:

作为普通的字典


推荐阅读