强制Visual Studio调试工具显示有用的信息

jth*_*h41 4 c# properties tostring typeconverter visual-studio-2013

众所周知,当你想在Visual Studio Debugger中查看复杂对象的内部变量时,你会得到类似这样的类名,你必须展开它才能看到公共属性:

在此输入图像描述

我试图使用这个问题的答案中的代码,而不是为每个类重写toString方法.

但它似乎没有任何区别.我还能尝试什么?

Adr*_*tti 6

你有很多选择,我会从最强大到最简单的展示它们.

自定义展示台

您可以查看Debugger Visualizers.您可以提供自己的UI来调试类.Idea本身与PropertyGrid编辑器的工作方式非常相似(IVisualObjectProvider并且DialogDebuggerVisualizer)您甚至可以重用该代码来使用属性网格检查对象.让我们看一个非常简单 - 未经测试的例子(改编自MSDN).

public class PropertyGridInspectorVisualizer : DialogDebuggerVisualizer
{
   protected override void Show(
                                IDialogVisualizerService windowService,
                                IVisualizerObjectProvider objectProvider)
   {
      var propertyGrid = new PropertyGrid();
      propertyGrid. Dock = DockStyle.Fill;
      propertyGrid.SelectedObject = objectProvider.GetObject();

      Form form = new Form { Text = propertyGrid.SelectedObject.ToString() };
      form.Controls.Add(propertyGrid);

      form.ShowDialog();
   }

   // Other stuff, see MSDN
}
Run Code Online (Sandbox Code Playgroud)

要使用此自定义可视化工具,您只需按照以下方式装饰您的类:

[DebuggerVisualizer(typeof(PropertyGridInspectorVisualizer))]
class Dimension
{
}
Run Code Online (Sandbox Code Playgroud)

代理对象

还有另一种方法可以获得对象的替代调试视图:DebuggerTypeProxyAttribute.您不会看到正在调试的对象,而是自定义代理(可以在所有类中共享并依赖TypeConverter).简而言之,它是这样的:

[DebuggerTypeProxy(CustomDebugView)]
class Dimension
{
}

// Debugger will show this object (calling its ToString() method
// as required and showing its properties and fields)
public class CustomDebugView
{
    public CustomDebugView(object obj)
    {
        _obj = obj;
    }

    public override string ToString()
    {
        // Proxy is much more powerful than this because it
        // can expose a completely different view of your object but
        // you can even simply use it to invoke TypeConverter conversions.
        return _obj.ToString(); // Replace with true code
    }

    private object _obj;
}
Run Code Online (Sandbox Code Playgroud)

非侵入式ToString()替换

最后一种方法(AFAIK)是使用DebuggerDisplayAttribute(MSDN的详细信息).您可以处理非常复杂的情况,但在许多情况下它非常方便:您构建一个字符串,当您检查该对象时,该字符串将由调试器显示.例如:

[DebuggerDisplay("Architectural dimension = {Architectural}")]
class Dimension
{
}
Run Code Online (Sandbox Code Playgroud)