debugging 如何让ToString()在调试中显示

0vvn1miw  于 2022-12-13  发布在  其他
关注(0)|答案(8)|浏览(202)

我想让ToString()在调试模式下为我控制的类显示。
如果这是当你用鼠标悬停在一个变量上时第一个显示的东西,那就太好了。

e3bfsja2

e3bfsja21#

使用标记类

[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

agxfikkp

agxfikkp2#

DebuggerDisplayAttribute可以影响显示,它允许你编写相当复杂的表达式来产生调试输出,尽管it is not recommended to do so
然而,如果你已经覆盖了ToString,那么调试器会默认显示它。

wfauudbj

wfauudbj3#

ToString的输出应该是您在调试时看到的默认值。
可以使用DebuggerDisplay属性(请参阅MSDN)覆盖它。
我更喜欢覆盖ToString方法,因为它更容易、更通用,因为它在写入日志文件时也有帮助。
如果你得到了类型名,你会看到默认的ToString

tkqqtvp1

tkqqtvp14#

I had a similar issue. My class had an ToString() override and it still didn't show up in VS, which was odd.
Adding the attribute [System.Diagnostics.DebuggerDisplay("{ToString()}")] to the class showed an exception in the visual studio debugger, where the ToString should have displayed. Turned out I had a bug with incorrectly using string.Format() in my implementation. This is an interesting behavior - VS reverts to the default ToString in case of an exception. The usage of the mentioned attribute forces the display to show the method's output - valid or exception. This is very useful for debugging ToString(). Otherwise there is no point in adding this attribute explicitly to each class since classes have it turned on by default, unless one wants to turn this behavior off for some reason.

1hdlvixo

1hdlvixo5#

您正在寻找的是DebuggerDisplayAttribute
http://www.codeproject.com/Articles/117477/Using-DebuggerDisplayAttribute
使用上面的链接来查看它是如何完成的,然后将它应用到你的类中,使用ToString()方法来驱动所显示的内容。

eanckbw9

eanckbw96#

重写.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()值

yfjy0ee7

yfjy0ee77#

如果您使用的是visual studio,则可以在yourvariable.ToString()行中添加watch @ runtime,当遇到断点时,它将显示在屏幕底部

nr7wwzry

nr7wwzry8#

我的问题是,尽管我覆盖了类中的ToString()方法,但调试器仍然没有显示ToString()的内容。原因是基类已经有一个DebuggerDisplay属性,而这个属性优先于 * 派生类 * 的ToString()方法。解决方法是将DebuggerDisplay属性也添加到派生类中:

[DebuggerDisplay("Name: {Name}")]
class Base
{
    public string Name { get; set; }
}

// Add this line to show the Address instead of Name in the debugger.
[DebuggerDisplay("{ToString()}")]
class Derived : Base
{
    public string Address { get; set; }

    public override string ToString()
    {
        return $"Address: {Address}";
    }
}

相关问题