DebuggerDisplay resolve to string at runtime
Is there a way to access the string shown by DebuggerDisplayAttribute
at runtime?
For our business objects i try to get automatic debugger information on exception handling. the actual object that was used while the exception was caught should be serialized to text to enhance the exception message. Since some attributes have other business objects as type, this could get really long if used recursively. Therefore i'd like to serialize to just the information that is already defined in DebuggerDisplay
attributes of the class. The ToString()
implementation of the classes can differ and are not usable for this task.
So is it possible to get the string that is shown in the debugger at runtime开发者_开发技巧?
I don't think so (at least not without some effort on your part) - I've just done a bit of digging around and found this an article about Debugger Display Best Practices. It's not directly related, but it does highlight one thing:
Each property {expression hole} must be evaluated individually and done so once for every instance of this type in every debugger display window.
I expect that it's using the debugger to do the evaluation once the code has been broken into (kind of similar to how you would use the immediate window to evaluate a statement when you're at a breakpoint).
The long and short of it is that the resulting debugger display value for an object is not available to you at runtime, unless you're willing to parse each of the expression holes and use reflection to evaluate them yourself.
The article suggests that the most efficient way to provide debugger output is to have a private method do a String.Format over all the properties you want to display. You might want to consider making this a public method (maybe on an interface) and use this to retrieve your exception information from.
Probably there is some way to extract that information, but wouldn't it be easier to redefine those classes with a property like this:
[DebuggerDisplay("{InfoProperty}")]
class X {
public string InfoProperty {
get { return "Debug and display info here"; }
}
}
Then you include that InfoProperty
in your error messages / logs instead of digging the way the data for display is reconstructed by Visual Studio.
Of course I am assuming that you can modify the business object classes, which might not be the case...
Technically, sure, it's possible - you could access the DebuggerDisplayAttribute at runtime with Reflection and write some code that parses the string and again uses Reflection to get the values. This won't work if you've got anything but properties and fields inside those curly braces, though.
In any case, I strongly suggest you heed Mike or Paolo's advice -if there are hundred of classes you need to change - then find a way to change them automatically - either with something like Resharper's Structural Search and Replace, or a Regular Expression - it shouldn't take too long.
精彩评论