【问题标题】:Display Subclass of List correctly in Debugger在调试器中正确显示 List 的子类
【发布时间】:2018-10-29 21:32:43
【问题描述】:

在我的程序中,我在这里写了一个List 的子类,称为BetterList

调试器显示如下:

我可以覆盖某些内容以使BetterList 正确显示吗?

【问题讨论】:

    标签: c# list debugging display


    【解决方案1】:

    对于这种情况,您应该使用DebuggerDisplayAttribute

    查看Enhancing Debugging with the Debugger Display Attribute 文档以获取有关它的更多详细信息以及一些具有更丰富功能的类似属性。

    【讨论】:

      【解决方案2】:

      假设新类公开了一个Count 属性,您可以在类中添加DebuggerDisplayAttribute 以在调试时显示该属性

      [DebuggerDisplay("Count = {Count}")]
      public class BetterList: List<SomeType> {
          //...
      
          public int Count { get; }
      }
      

      对于更复杂的显示场景请查看Using DebuggerTypeProxy Attribute

      DebuggerTypeProxyAttribute 为类型指定代理或替代,并更改类型在调试器窗口中的显示方式。当您查看具有代理的变量时,代理代表显示中的原始类型。调试器变量窗口仅显示代理类型的公共成员。不显示私人成员。

      [DebuggerDisplay("Count = {Count}")]
      [DebuggerTypeProxy(typeof(BetterListDebuggerView))]
      public class BetterList: List<SomeType> {
          //...
      
          public int Count { get; }
      
          internal class BetterListDebuggerView {
              private BetterList list;
              public BetterListDebuggerView(BetterList list) {
                  this.list = list;
              }
      
              [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
              public SomeType[] Items {
                  get {
                      return list.ToArray();
                  }
              }
          }
      }
      

      【讨论】:

      • 好的,我可以用它来显示列表值吗?就像当你展开列表时你会看到它的成员,而当你展开 betterList 时你只会看到列表的 RawView
      • @JavaJawa 有一个 DebuggerTypeProxyAttribute 用于更复杂的自定义。
      猜你喜欢
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-18
      • 2023-03-10
      • 2019-04-02
      • 2017-12-09
      • 1970-01-01
      相关资源
      最近更新 更多