5

.NET中使用DebuggerDisplay轻松定制调试

 3 years ago
source link: http://www.cnblogs.com/yyfh/p/14399282.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前言

对于调试的方式有多种,不过在今天我们将看到的监视窗口对变量的监视,当然在这里我们是定制内部的变量值,或者说变量的显示与计算的内容。

注:监视窗口在调试时可以一次显示多个变量。“快速监视”对话框一次显示一个变量。

Eb2eie.png!mobile

DebuggerDisplayAttribute

在下面示例中,我们在类上添加 DebuggerDisplay ,添加字符串:("Name={Name},Age={Age}"):

class Program
    {
        static void Main(string[] args)
        {
            Student student = new Student()
            {
                Name = "Mr.A",
                Age = 18
            };

            Console.WriteLine("Hello World!");
        }

        [DebuggerDisplay("Name={Name},Age={Age}")]
        class Student
        {
            public int Age { get; set; }

            public string Name { get; set; }
        }
    }

如下图,在调试模式下,我们可以将鼠标箭头放到变量上去,从而看到变量的值,也可以看到我们定义好的字符串内容格式:

iURzmeB.png!mobile

进一步来看一下,我们定义一个属性,将属性的内容呈现出来,代码片段如下所示:

[DebuggerDisplay("{DebuggerDisplay,nq}")]
        public struct Point
        {
            public int X { get; }
            public int Y { get; }

            public Point(int x, int y)
            {
                X = x;
                Y = y;
            }
            private string DebuggerDisplay => $"{X},{Y}";
        }

对于结果已经呈现出来了,我们可以看到我们在 DebuggerDisplay 属性中定义的内容,同时我们看的是没有引号,是的,这一点很重要,对于 nq 的话他主要删除引号,因为我们在这里采用的是字符串,所以可通过 nq 进行引号的删除

ZVfiIfB.png!mobile

DebuggerBrowsableAttribute

对于 DebuggerBrowsableAttribute 特性来说的话,他应用于属性字段,可控制它们的显示方式,通过枚举类型 DebuggerBrowsableState 来控制字段属性的显示行为:

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static string y = "Test String";

DebuggerBrowsableState

  • Never 可隐藏字段属性
  • Collapsed 默认选项,显示成员信息
  • RootHidden 不显示字段,如果是数组或者集合将以成对的对象形式显示

DebuggerTypeProxyAttribute

DebuggerTypeProxyAttribute 属性用于指定代理类型显示,它允许我们为类型定制视图,如果找到这个属性,则表达式评估其将显示代理类型替换为该属性所应用的类型,这其实对我们来公开原始类型以外的属性很有用。下面我们看一下代码示例:

[DebuggerTypeProxy(typeof(SampleDebugView))]
    public class Sample
    {
        public string Name { get; set; }

        private class SampleDebugView
        {
            private readonly Sample _sample;

            public SampleDebugView(Sample sample)
            {
                _sample = sample;
            }

            public string Name => _sample.Name;
            public int NameLength => _sample.Name.Length;

            [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
            public char[] NameCharacters => _sample.Name.ToCharArray();
        }
    }

可以看到下图,我们通过代理视图的方式将我们的信息都展开,这样更方便我们对信息的调试显示

aaMR7vF.png!mobile

Reference

https://docs.microsoft.com/zh-cn/dotnet/api/system.diagnostics.debuggerbrowsableattribute


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK