Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

.net - Can the DebuggerDisplay attribute be applied to types one doesn't own?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


Edit 2020:

Was not able to reproduce the above for KeyValuePair<,> in VS2019 but it seems to be related to KeyValuePair<,>.

For private member of non owned types try something like this

ClassLibrary1:

//using System.Diagnostics;

namespace ClassLibrary1
{
    //[DebuggerDisplay("Foo.Bar={Bar}")] // works too for types you own
    public class Foo
    {
        private int Bar = 42;
    }
}

ConsoleApp1:

using System.Diagnostics;
using System.Reflection;
using ClassLibrary1;

[assembly: DebuggerDisplay("Foo.Bar={FooDebuggerDisplay.Bar(this)}", Target=typeof(Foo))]

class FooDebuggerDisplay
{
    public static int Bar(Foo foo) => (int)foo.GetType().GetField("Bar",BindingFlags.Instance|BindingFlags.NonPublic).GetValue(foo);
}

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var foo = new Foo();
            Debugger.Break();
        }
    }
}

(Tested in VS2019)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...