C# debugging and testing | DebuggerDisplay skills

insert image description here

DebuggerDisplay usage skills

foreword

Debugging is an unavoidable task when you are developing a large application. The debugger is your best friend, but sometimes it doesn't give you the information you need directly. At this time, you need to use a very useful Attribute in C#: DebuggerDisplay .

About Attribute
Attribute is a special class in C#, which can add metadata to elements such as classes, methods, and attributes at compile time. At runtime, this metadata can be used by the reflection mechanism. It is a very powerful metaprogramming tool that allows you to obtain more information at runtime.

Introduction to DebuggerDisplay

DebuggerDisplay allows you to display your own defined strings in the debugger instead of the default display. In other words, it allows you to view object information more conveniently in the debugger.

When you are debugging a complex object, you often find that the default display method cannot meet your needs. At this time, you can use DebuggerDisplay to customize the information you want to display. For example, you can display the values ​​of some important properties or fields in the debugger, so that you can more easily understand the state of the object. In addition, if you use some custom classes, these classes may not have a default ToString method, and the default display method of the debugger will be very simple. At this time, you can use DebuggerDisplay to define a more friendly display method.

sample code

Next we use a sample code to demonstrate how to use DebuggerDisplay.

First, we define a Person class and add DebuggerDisplay Attribute to it.

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

Instantiate a Person object in the Main method and output it to the console.

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        var person = new Person {
    
     Name = "张三", Age = 20 };
        Console.WriteLine(person); // 在这里添加一个断点
    }
}

Since we defined the DebuggerDisplay Attribute, the debugger will display our own defined string, namely "Name = Zhang San, Age = 20". In this way, we can more easily understand the state of the Person object.

Guess you like

Origin blog.csdn.net/lgj123xj/article/details/130143363