Possible to accessing child “DebuggerDisplay” attribute of property?

前端 未结 3 888
温柔的废话
温柔的废话 2021-02-19 22:49

Current state

Having two classes:

[DebuggerDisplay(@"One = {One}, two = {Two}")]
public class A
{
    public int One { get; set; }
    public B         


        
3条回答
  •  礼貌的吻别
    2021-02-19 23:41

    Piecing together a few things I've come up with this solution. It has the caveat it expects you to follow https://blogs.msdn.microsoft.com/jaredpar/2011/03/18/debuggerdisplay-attribute-best-practices/

    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class B
    {
        public int Three { get; set; }
    
        private string DebuggerDisplay => $"Three = {Three}";
    }
    
    [DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class A
    {
        public int One { get; set; }
        public B Two { get; set; }
    
        private string DebuggerDisplay => $"One = {One}, two = {Two.ReadDebuggerDisplay()}";
    }
    

    You'll need to make sure you have proper imports for where ever you stick this helper in relation to the code that needs to read child debugger displays.

    public static class ReflectionHelper
    {
        // https://stackoverflow.com/a/13650728/37055
        public static object ReadProperty(
            this object target,
            string propertyName)
        {
            var args = new[] {CSharpArgumentInfo.Create(0, null)};
            var binder = Binder.GetMember(0, propertyName, target.GetType(), args);
            var site = CallSite>.Create(binder);
            return site.Target(site, target);
        }
    
        public static string ReadDebuggerDisplay(
            this object target, 
            string propertyName = "DebuggerDisplay")
        {
            string debuggerDisplay = null;
            try
            {
                var value = ReadProperty(target, propertyName) ?? "";
    
                debuggerDisplay = value as string ?? value.ToString();
            }
            catch (Exception)
            {
                // ignored
            }
            return debuggerDisplay ?? 
                  $"";
        }
    }
    

    I feel like this a pretty fair balance of purity and pragmatism for lowering the friction on achieving this. If you are less concerned about purity you could just make DebuggerDisplay public. I prefer that the ReadDebuggerDisplay operates in a "type-less" manner (avoids generic constraints and interfaces that would be needed to access DebuggerDisplay publicly).

提交回复
热议问题