确实存在一个方法来呈现使用DebuggerDisplayAttribute一个目的目的、方法来、确实、存在

2023-09-03 16:55:12 作者:眼里有你

我有许多被装饰着DebuggerDisplayAttribute类。

我希望能够跟踪语句添加到单元测试会显示这些类的实例。

是否存在.NET Framework中的一个方法,将显示格式化对象使用DebuggerDisplayAttribute(或退回到使用的ToString(),如果没有DebuggerDisplayAttribute定义)?

修改

要澄清,我希望有可能是一个内置的框架。我知道我可以从DebuggerDisplayAttribute值属性,但我需要使用格式字符串再由DebuggerDisplayAttribute.Value psented $ P $格式化我的实例。

宁波博仕胃肠病医院 肠道毒素累积的危害

如果我摇我自己,我会设想大致如下的扩展方法:

 公共字符串FormatDebugDisplay(该对象的值)
{
    DebugDisplayAttribute属性= ...获取值的属性...
    如果(属性= NULL)返回value.ToString();

    字符串的formatString = attribute.Value;

    ???如何在使用的formatString格式值???
    返回SomeFormatMethod(formatString中,值);
}
 

解决方案

这可能是好的 - 但DebuggerDisplayAttribute的格式字符串由调试评估,键入到监视窗口或同样的方式计算EX pressions立即窗口。这就是为什么你可以把任意EX pressions的括号内,如 {姓++姓氏}

因此​​,在code,以评估这些,你就需要嵌入Visual Studio调试器到你的应用程序。也许不会发生的。 (笑)

您最好的选择可能是把所有的格式逻辑是目前在DebuggerDisplay格式字符串,并使其成为一个方法来代替。然后,你可以自由地从你的code调用该方法。你DebuggerDisplay属性最终无所作为,但调用该方法。

  [DebuggerDisplay({检查()})]
公共MyClass类{
    公共字符串检查(){...}
}
 

I have a number of classes that are decorated with DebuggerDisplayAttribute.

I want to be able to add trace statements to Unit Tests that will display instances of these classes.

Does there exist a method in the .NET Framework that will display an object formatted using DebuggerDisplayAttribute (or fall back to using .ToString() if no DebuggerDisplayAttribute is defined)?

EDIT

To clarify, I was hoping there might be something built into the Framework. I know I can get the Value property from DebuggerDisplayAttribute, but I then need to format my instance using the format string represented by DebuggerDisplayAttribute.Value.

If I roll my own, I'd envisage an extension method along the following lines:

public string FormatDebugDisplay(this object value)
{
    DebugDisplayAttribute attribute = ... get the attribute for value ...
    if (attribute = null) return value.ToString();

    string formatString = attribute.Value;

    ??? How do I format value using formatString ???
    return SomeFormatMethod(formatString, value);
}

解决方案

That might be nice -- but DebuggerDisplayAttribute's format string is evaluated by the debugger, the same way it evaluates expressions you type into the Watch windows or the Immediate window. That's why you can put arbitrary expressions inside the braces, like {FirstName + " " + LastName}.

Therefore, to evaluate these in your code, you would need to embed the Visual Studio debugger into your app. Probably not gonna happen. (grin)

Your best bet is probably to take all the formatting logic that's currently in your DebuggerDisplay format string, and make it a method instead. Then you're free to call that method from your code. Your DebuggerDisplay attribute ends up doing nothing but calling the method.

[DebuggerDisplay("{Inspect()}")]
public class MyClass {
    public string Inspect() { ... }
}