Can the DebuggerDisplay attribute be applied to ty

2019-01-08 21:08发布

问题:

I like the DebuggerDisplay attribute. I like it so much, that I want to use it on types that I don't have the source code for.

Is this possible?

回答1:

Example of setting DebuggerDisplay for a foreign type (System.Collections.Generic.KeyValuePair<TKey,TValue>) add the following to AssemblyInfo.cs:

using System.Collections.Generic;
using System.Diagnostics;

[assembly: DebuggerDisplay("[Key={Key}, Value={Value}]", Target = typeof(KeyValuePair<,>))]

(Tested in VS2015)



回答2:

Yes. In fact, Microsoft was so nice as to make this a built-in option in Visual Studio.

Look up the "My Documents\Visual Studio 20XX\autoexp.cs" for some examples of how you apply the DebuggerDisplay attribute to types that are foreign to your assembly. Then, add some of your own, recompile it and replace the autoexp.dll, and restart Visual Studio. It should Just Work.

For reference, see the yellow "Note" paragraph in this MSDN article


Alternatively: I'm the creator of a purchasable extension to Visual Studio that enables doing this with a lot less fuss, without even needing to have to stop the debugging session.



回答3:

Attributes are a way to decorate something (types, methods, fields, etc) at compile time and they are stored in the binary representation of an assembly. One way to add a new attribute in it is to recompile the code with the new attribute. If you don't have the code, in some cases, you might get the code by decompiling the assembly.

Another way I can think of, might be to use Reflection to load and process all the types in an assembly and then generate (through reflection) another assembly with DebuggerDisplay added to the types you want (here's an example)