如何让 ToString() 显示在 Debug 中

问题描述 投票:0回答:8

我希望在调试模式下显示我控制下的类。

如果这是当您将鼠标悬停在变量上时首先显示的内容,那就太好了。有这个属性吗?

c# .net debugging visual-studio-debugging
8个回答
33
投票
标记你的班级

ToString()

测试:

[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; } }

    


10
投票

This is the text that will be displayed at debugging

 可让您影响显示。它允许您编写相当复杂的表达式来生成调试输出,尽管
不建议这样做 但是,如果您覆盖了

DebuggerDisplayAttribute

,则调试器会被记录为默认显示该内容。也许代码有问题?

    


7
投票
ToString

的输出应该是调试时看到的默认输出。


可以使用

ToString

属性覆盖它(请参阅

MSDN
)。 我更喜欢覆盖

DebuggerDisplay

方法,因为它更简单、更通用,因为它在写入日志文件时也很有帮助。


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

ToString

    


7
投票

将属性 [System.Diagnostics.DebuggerDisplay("{ToString()}")] 添加到类中会在 Visual Studio 调试器中显示异常,而 ToString 应该显示在其中。事实证明,我在实现中遇到了错误使用 string.Format() 的错误。 这是一个有趣的行为 - VS 在发生异常时恢复默认的 ToString。 使用上述属性会强制显示该方法的输出 - 有效或异常。这对于调试 ToString() 非常有用。否则,没有必要向每个类显式添加此属性,因为类默认打开该属性,除非出于某种原因想要关闭此行为。


4
投票
ToString


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

使用上面的链接查看它是如何完成的,然后将其应用到您的类中,使用

DebuggerDisplayAttribute

方法来驱动显示的内容。我只使用过属性,不确定是否可以注入类。

    


2
投票

ToString()

这将返回 Property3 作为 ToString() 值


0
投票


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

方法,但调试器仍然没有显示

ToString()
内容。原因是基类已经具有
ToString()
属性,并且该属性优先于
派生类
DebuggerDisplay
方法。解决方案是将 ToString() 属性也添加到派生类:
DebuggerDisplay

© www.soinside.com 2019 - 2024. All rights reserved.