如何在Debug中显示ToString()

我想在调试模式下让ToString()显示我控制下的类。

当你用鼠标hover在一个变量上时,这是第一个出现的东西。 这有属性吗?

用你的课标记你的课程

[System.Diagnostics.DebuggerDisplay("{ToString()}")] 

测试:

 [System.Diagnostics.DebuggerDisplay("{ToString()}")] class MyClass { private string _foo = "This is the text that will be displayed at debugging" public override string ToString() { return _foo; } } 

现在,当您使用鼠标将鼠标hover在变量上时,它将显示This is the text that will be displayed at debugging

DebuggerDisplayAttribute可以让您影响显示。 它允许您编写相当复杂的表达式来生成调试输出,但不建议这样做 。

但是,如果您已重写ToString ,则会记录调试器以在默认情况下显示该调试器。 也许代码有问题?

您正在寻找的是DebuggerDisplayAttribute

http://www.codeproject.com/Articles/117477/Using-DebuggerDisplayAttribute

使用上面的链接查看它是如何完成的,然后将其应用于您的类,使用ToString()方法来驱动显示的内容。 我只使用过属性,不确定是否可以注入类。

ToString的输出应该是您在调试时看到的默认值。

可以使用DebuggerDisplay属性覆盖它(请参阅MSDN )。

我更喜欢重写ToString方法,因为它更容易,更通用,因为它在写入日志文件时也有帮助。

你看到什么输出? 如果获得类型名称,则会看到默认的ToString

在对象中覆盖.ToString,如下所示:

 public class MyObject { public int Property1{ get; set; } public string Property2{ get; set; } public string Property3 { get; set; } public override string ToString() { return Property3; } } 

这将返回Property3作为ToString()值

我有一个类似的问题。 我的类有一个ToString()覆盖,它仍然没有显示在VS中,这很奇怪。

将属性[System.Diagnostics.DebuggerDisplay(“{ToString()}”)]添加到类中会在visual studio调试器中显示exception,其中应显示ToString。 原来我在我的实现中错误地使用了string.Format()。 这是一个有趣的行为 – 如果出现exception,VS将恢复为默认的ToString。 使用上述属性会强制显示器显示方法的输出 – 有效或exception。 这对于调试ToString()非常有用。 否则,将此属性显式添加到每个类是没有意义的,因为默认情况下类已启用它,除非有人因某种原因想要关闭此行为。

如果你正在使用visual studio,你可以添加一个watch @ runtime和你的变量.ToString()行,当它遇到断点时会显示在你的屏幕底部