这篇文章讲述如何自定义你的调试窗体。这些技巧在你调试应用程序的时候是非常有用的。当你调试的时候,你可能希望简化调试窗体的信息,或者在调试窗体上除去对你不重要的不必要的信息,这篇文章将会帮助到你。本文翻译:Few Tips on Customizing Debugging Window View in Visual Studio 。
使用DebuggerBrowsable特性可以自定义调试窗体。
使用DebuggerDisplay特性可以自定义调试信息的显示。
要使用这些特性,需要引用System.Diagnostics命名空间。
技巧1、使用DebuggerBrowsable特性
你可以通过在属性上使用DebuggerBrowsable特性来自定义调试窗体。这些特性可以用任何属性、字段和索引上。DebuggerBrowsable的构造函数需要一个DebuggerBrowsableState 参数。DebuggerBrowsableState用来指定调试信息在窗体上显示的方式。
它有三个状态:
1、Collapsed :如果设置DebuggerBrowsableState为Collapsed 。那么调试信息折叠显示。默认为Collapsed
2、Never :调试窗体不显示调试信息
3、RootHidden :隐藏调试信息的根元素,只显示子元素信息,想了解更多,看MSDN。
下面我将通过一个例子叙述如何使用DebuggerBrowsable 和DebuggerBrowsableState。开始之前,看下面这段代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
class
Program
{
static
void
Main(
string
[] args)
{
List<Student> student =
new
List<Student>();
student.Add(
new
Student { Roll = 1, Name =
"Abhijit"
, Marks = 87, Addresses =
new
Address { Address1 =
"add1"
, Address2 =
"add2"
} });
student.Add(
new
Student { Roll = 2, Name =
"Abhishek"
, Marks = 41, Addresses =
new
Address { Address1 =
"add3"
, Address2 =
"add4"
} });
student.Add(
new
Student { Roll = 3, Name =
"Rahul"
, Marks = 67, Addresses =
new
Address { Address1 =
"add5"
, Address2 =
""
} });
student.Add(
new
Student { Roll = 4, Name =
"Sunil"
, Marks = 91, Addresses =
new
Address { Address1 =
"add11"
, Address2 =
"add122"
} });
student.Add(
new
Student { Roll = 5, Name =
"Atul"
, Marks = 71, Addresses =
new
Address { Address1 =
"add12"
, Address2 =
"add222"
} });
student.Add(
new
Student { Roll = 6, Name =
"Kunal"
, Marks = 71, Addresses =
new
Address { Address1 =
"add12"
, Address2 =
"add222"
} });
}
/// <summary>
/// Student Class
/// </summary>
class
Student
{
public
int
Roll {
get
;
set
; }
public
string
Name {
get
;
set
; }
public
int
Marks {
get
;
set
; }
public
Address Addresses {
get
;
set
; }
}
/// <summary>
/// Address of Students
/// </summary>
class
Address
{
public
string
Address1 {
get
;
set
; }
public
string
Address2 {
get
;
set
; }
}
}
|
下面,先看一下不使用这些特性是什么样的效果。我在main 函数的结尾放置一个断点。你可以得到下面的调试窗体。
从上图中可以看到有6个student对象,每个对象的值都不同。Addresses是类Address的对象,它的调试信息值是隐藏的。
现在,我想要看到address的所有属性信息,隐藏Marks 属性。为了实现这样的需求,需要为给student 类中的Marks 和Addresses属性添加DebuggerBrowsable特性。
调试信息显示如下图:
技巧2、使用DebuggerDisplay特性
使用DebuggerDisplay可以定义类和字段在调试窗体中如何显示。使用 DebuggerDisplay可以改变调试窗体中显示的信息和变量,使它显示你想要的信息。
看下面没有使用DebuggerDisplay 的调试窗体。
默认情况下,每一个study对象你只得到NameSpace.ClassName这样的显示信息。我们可以使用DebuggerDisplay来自定义显示的信息。DebuggerDisplay 构造函数需要显示名作为参数。你可以传递指定参数来显示。做如下设置:
看下效果:
使用DebuggerDisplay的时候必须注意,在{}中必须给出类的正确属性。
如我将Roll写成Rolls,如下图:
调试窗体会提示:The name 'Rolls' does not exist in the current context。如下图:
总结:本文讲述了使用DebuggerBrowsable 和DebuggerDisplay两个特性来自定义调试窗体的显示。当你调试一个非常复杂的对象时,这个是非常有用的,它可以使你的调试窗体非常简单。