c# - 仅在 VisualStudio 的调试器中按键对字典进行排序
问题描述
我在我的应用程序中使用基于 Dictionary 的对象。调试时(并且仅当我检查字典时)我想查看字典的内容,但按键排序。
我知道我可以使用 SortedDictionary 而不是 Dictionary 但与 Dictionary 相比性能较差,我不想影响性能。
我也不想有“#if debug”条件。
可能吗 ?
解决方案
你可以在你的类上指定一个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 的类的排序输出:
以及不使用任何代理来显示其数据的“普通”字典的未排序输出:
推荐阅读
- node.js - 返回的数组具有未定义的值
- .net - 如何同时根据元素数量或聚合总和在 linq 中进行分组?
- cloud-foundry - 如何停止在 Cloud Foundry 中重新创建服务
- c++ - 调用函数时的 C++ Null 输出
- static - next.js getStaticPaths 列出每条路径还是仅列出附近的路径?
- testing - Jmeter 重定向挑战
- typescript - 使用 TypeScript 编译器 API 获取变量初始值设定项的解析类型(和 jsdoc 标签)
- python - 在单元测试中设置 HttpReferrer
- cassandra - Cassandra 代币分发
- javascript - 旋转具有绝对位置的 img