How to make [DebuggerDisplay] respect inherited classes or at least work with collections?

后端 未结 3 561
名媛妹妹
名媛妹妹 2020-12-31 07:21

I\'ve got a class which inherits from a List. It works well and as expected in all respects except one: when I add the [DebuggerDisplay]<

3条回答
  •  自闭症患者
    2020-12-31 07:57

    You can get the effect you need by using the DebuggerTypeProxy attribute. You need to create a class to make a debug "visualisation" of your inherited list:

    internal sealed class MagicBeanListDebugView
    {
        private List list;
    
        public MagicBeanListDebugView(List list)
        {
            this.list = list;
        }
    
        [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
        public MagicBean[] Items{get {return list.ToArray();}}
    }
    

    You can then declare this class to be used by the debugger for displaying your class, along with the DebuggerDisplay attribute:

    [DebuggerDisplay("Count = {Count}")]
    [DebuggerTypeProxy(typeof(MagicBeanListDebugView))]
    public class MagicBeanList : List
    {}
    

    This will give you the "Count = 3" message when you hover over an instance of your inherited list in Visual Studio, and a view of the items in the list when you expand the root node, without having to drill down into the base properties.

    Using ToString() to specifically get debug output is not a good approach, unless of course you are already overriding ToString() for use in your code elsewhere, in which case you can make use of it.

提交回复
热议问题