【发布时间】:2014-06-26 20:13:17
【问题描述】:
众所周知,当你想在 Visual Studio 调试器中查看复杂对象的内部变量时,你会得到类似这样的类名,你必须展开才能看到公共属性:
我正在尝试使用this question 答案中的代码,而不是为每个类重写 toString 方法。
但这似乎没有任何区别。我还能尝试什么?
【问题讨论】:
标签: c# properties visual-studio-2013 tostring typeconverter
众所周知,当你想在 Visual Studio 调试器中查看复杂对象的内部变量时,你会得到类似这样的类名,你必须展开才能看到公共属性:
我正在尝试使用this question 答案中的代码,而不是为每个类重写 toString 方法。
但这似乎没有任何区别。我还能尝试什么?
【问题讨论】:
标签: c# properties visual-studio-2013 tostring typeconverter
你有很多选择,我会从最强大到最简单的一种来展示它们。
您可以查看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
}
要使用此自定义可视化工具,您只需按如下方式装饰您的类:
[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;
}
最后一种方法(AFAIK)是使用DebuggerDisplayAttribute(详情请使用MSDN)。您可以处理非常复杂的情况,但在许多情况下非常方便:您构建一个字符串,当您检查该对象时,调试器将对其进行可视化。例如:
[DebuggerDisplay("Architectural dimension = {Architectural}")]
class Dimension
{
}
【讨论】: