如何使 DebuggerDisplay 适用于 Dictionary 中的复合类型?
How to make DebuggerDisplay work for composite types in Dictionary?
为了愉快地显示 Dictionary
的内容,我写了这个:
[assembly: DebuggerDisplay("{Key,nq} -> {Value,nq}", Target = typeof(KeyValuePair<,>))]
namespace test {
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Thing {
private readonly int _num;
public string DebuggerDisplay => $"DBG: {_num}";
public Thing(int num) => _num = num;
}
public class Program {
static void Main(string[] args) {
var map = new Dictionary<string,Thing> {
["Foo"] = new Thing(1),
["Bar"] = new Thing(2),
};
}
}
}
我希望在调试器中看到这个:
Foo -> DBG: 1
Bar -> DBG: 2
但我看到的是:
Foo -> {test.Thing}
Bar -> {test.Thing}
值得注意的是,如果我展开 KeyValuePair
中的一个,我会看到:
Name | Value
--------+-------
Key | "Foo"
Value | DBG: 1
所以 DebuggerDisplay
确实有效。
所以问题是如何在字典内容的主观察列表中显示复合类型的内容?
虽然 DebuggerDisplay
的嵌套评估不起作用,但它实际上足够灵活,可以调用任何带有参数的自定义格式设置方法。所以我会这样做:
[assembly:DebuggerDisplay("{Key,nq} -> {MyNamespace.DebugHelper.DisplayValue(this.Value),nq}", Target = typeof(KeyValuePair<,>))]
调试助手可以是内部助手class:
internal static class DebugHelper
{
internal static string DisplayValue(object value)
{
switch (value)
{
case Thing thing:
return thing.DebuggerDisplay; // or even better just to format it here
default:
return value.ToString();
}
}
}
为了愉快地显示 Dictionary
的内容,我写了这个:
[assembly: DebuggerDisplay("{Key,nq} -> {Value,nq}", Target = typeof(KeyValuePair<,>))]
namespace test {
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Thing {
private readonly int _num;
public string DebuggerDisplay => $"DBG: {_num}";
public Thing(int num) => _num = num;
}
public class Program {
static void Main(string[] args) {
var map = new Dictionary<string,Thing> {
["Foo"] = new Thing(1),
["Bar"] = new Thing(2),
};
}
}
}
我希望在调试器中看到这个:
Foo -> DBG: 1
Bar -> DBG: 2
但我看到的是:
Foo -> {test.Thing}
Bar -> {test.Thing}
值得注意的是,如果我展开 KeyValuePair
中的一个,我会看到:
Name | Value
--------+-------
Key | "Foo"
Value | DBG: 1
所以 DebuggerDisplay
确实有效。
所以问题是如何在字典内容的主观察列表中显示复合类型的内容?
虽然 DebuggerDisplay
的嵌套评估不起作用,但它实际上足够灵活,可以调用任何带有参数的自定义格式设置方法。所以我会这样做:
[assembly:DebuggerDisplay("{Key,nq} -> {MyNamespace.DebugHelper.DisplayValue(this.Value),nq}", Target = typeof(KeyValuePair<,>))]
调试助手可以是内部助手class:
internal static class DebugHelper
{
internal static string DisplayValue(object value)
{
switch (value)
{
case Thing thing:
return thing.DebuggerDisplay; // or even better just to format it here
default:
return value.ToString();
}
}
}