gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:40:48 26 4
gpt4 key购买 nike

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

enter image description here

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

不过好像没什么区别。我还能尝试什么?

最佳答案

您有很多选择,我将从最强大到最简单的方式展示它们。

自定义可视化工具

你可以看看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
{
}

代理对象

还有另一种方法可以获得对象的替代调试 View :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() 替换

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

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

关于c# - 强制 Visual Studio 调试工具显示有用的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24439401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com