简体   繁体   中英

DebuggerDisplay on generic class

I have a problem applying the DebuggerDisplay attribute on a generic class:

[DebuggerDisplay("--foo--")]
class Foo
{
}

[DebuggerDisplay("Bar: {t}")]
class Bar<T>
{
    public T t;
}

When inspecting an object of type Bar<Foo> I would expect it to show as Bar: --foo-- , but I get Bar: {Foo}

What am I doing wrong?

The DebuggerDisplay attribute is not recursive. The {} inside the string essentially say evaluate this expression and display the result inline. The string for the inner result is calculated as if there was no DebuggerDisplay attribute in play for type or member. That is why you see {Foo} instead of --foo--.

The reason for this is reliability. It is far too easy to have mutually recursive DebuggerDisplay attribute tags. This would cause a stack overflow or infinite loop to occur when evaluating an inner expression. Not recursively evaluating the DebuggerDisplay attribute prevents this infinite recursion (although it's still quite possible for the user to create it themselves inside a particular expression).

One way you can control the way the inner expression is displayed is by overriding the .ToString() method. This will be evaluated when computing the display string for an inner expression.

You can use [DebuggerDisplay("Bar<{typeof(T).Name}>,nq}")]//nq - no quotes .

You also can use these practices: DebuggerDisplay attribute best practices

[Disclaimer: I'm affiliated with OzCode]

You can use OzCode's Reveal feature which supports nested/recursive debug information. 在此输入图像描述
Once you define it for an instance it would be used automatically for all instances of that type.

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