我希望在调试模式下显示我控制下的类。
如果这是当您将鼠标悬停在变量上时首先显示的内容,那就太好了。有这个属性吗?
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;
}
}
。
This is the text that will be displayed at debugging
可让您影响显示。它允许您编写相当复杂的表达式来生成调试输出,尽管不建议这样做。 但是,如果您覆盖了
DebuggerDisplayAttribute
,则调试器会被记录为默认显示该内容。也许代码有问题?
将属性 [System.Diagnostics.DebuggerDisplay("{ToString()}")] 添加到类中会在 Visual Studio 调试器中显示异常,而 ToString 应该显示在其中。事实证明,我在实现中遇到了错误使用 string.Format() 的错误。 这是一个有趣的行为 - VS 在发生异常时恢复默认的 ToString。 使用上述属性会强制显示该方法的输出 - 有效或异常。这对于调试 ToString() 非常有用。否则,没有必要向每个类显式添加此属性,因为类默认打开该属性,除非出于某种原因想要关闭此行为。
ToString()
这将返回 Property3 作为 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;
}
}
方法,但调试器仍然没有显示
ToString()
内容。原因是基类已经具有 ToString()
属性,并且该属性优先于 派生类的
DebuggerDisplay
方法。解决方案是将 ToString()
属性也添加到派生类:DebuggerDisplay