简体   繁体   中英

How do I use a delegate other than ToString to show an object's value while debugging?

.NET/Visual Studio uses an object's ToString() method to display the value of an object when viewing it in the debugger. I would like to display specific information, but since .ToString() is often used by the framework when converting an object to a string, I cannot do it by overriding ToString(). Is there an attribute I can use to tell the debugger to use a different method or property?

Use the DebuggerDisplayAttribute [MSDN] . You supply it with a format string that references fields/properties within the class to display while debugging without having to mess with ToString() .

[DebuggerDisplay("Count = {count}")]
class MyHashtable
{
    public int count = 4;
}

It also works with methods:

[DebuggerDisplay("{ToDebugString()}")]
public class SomeClass
{
    public override String ToString()
    {
        return "Normal ToString()";
    }

    public String ToDebugString()
    {
        return "ToDebugString()";
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM