![](/img/trans.png)
[英]How to make [DebuggerDisplay] respect inherited classes or at least work with collections?
[英]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<,>))]
調試幫助程序可以作為內部幫助程序類的地方:
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();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.