【问题标题】:Forcing Visual Studio Debugging Tools to display useful information强制 Visual Studio 调试工具显示有用信息
【发布时间】:2014-06-26 20:13:17
【问题描述】:

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

我正在尝试使用this question 答案中的代码,而不是为每个类重写 toString 方法。

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

【问题讨论】:

标签: c# properties visual-studio-2013 tostring typeconverter


【解决方案1】:

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

自定义展示台

您可以查看Debugger Visualizers。您可以提供自己的 UI 来调试您的类。 Idea 本身与PropertyGrid 编辑器的工作方式(IVisualObjectProviderDialogDebuggerVisualizer)非​​常相似,您甚至可以重用该代码以使用属性网格检查您的对象。让我们看一个非常琐碎且未经测试的示例(改编自 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
}

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

[DebuggerVisualizer(typeof(PropertyGridInspectorVisualizer))]
class Dimension
{
}

代理对象

还有另一种方法可以获得对象的替代调试视图: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;
}

非侵入性 ToString() 替换

最后一种方法(AFAIK)是使用DebuggerDisplayAttribute(详情请使用MSDN)。您可以处理非常复杂的情况,但在许多情况下非常方便:您构建一个字符串,当您检查该对象时,调试器将对其进行可视化。例如:

[DebuggerDisplay("Architectural dimension = {Architectural}")]
class Dimension
{
}

【讨论】:

    【解决方案2】:

    [免责声明:我为OzCode工作]

    内置的 VS 功能,如 DebuggerDisplayAttribute、DebuggerTypeProxy 和自定义可视化工具可能对您有用(并在其他答案中描述)。它们的问题在于它们都有自己的局限性,更重要的是它们是固定的和硬编码的。

    如果我需要查看不同调试会话的不同信息,我希望这样做而不编写/更新另一个类并编译/部署我的代码。

    我建议你尝试使用 OzCode 的 Reveal: 使用小“星”,您可以选择查看该课程时将显示哪些信息。如果您需要更改类在调试器中的外观 - 只需单击您想查看的成员即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多