幾招教會(huì)您VS調(diào)試?yán)Щ?/h1>
在VS調(diào)試代碼中,我們經(jīng)常會(huì)遇到這樣的問(wèn)題,有時(shí)我們引用了一些其他工具包或者類(lèi)庫(kù)(如Microsoft提供的Enterprise Library),而在VS調(diào)試時(shí),我們其實(shí)是不需要跟蹤VS調(diào)試這些代碼的,因?yàn)樗鼈兌家呀?jīng)證明是正確的。在Visual Studio 2003中,處理這類(lèi)問(wèn)題我們的方法一般是使用F10跳過(guò)它們,但一旦工程龐大的話(huà),這樣做十分麻煩。
JMC功能由兩方面來(lái)實(shí)現(xiàn)。首先,如果一個(gè)工程是以release方式進(jìn)行編譯構(gòu)建的話(huà)(就是工程中,沒(méi)有pdb文件),VS調(diào)試器會(huì)將其認(rèn)為是非用戶(hù)代碼,那么在VS調(diào)試運(yùn)行時(shí),就根本不會(huì)進(jìn)入該工程中進(jìn)行VS調(diào)試。其次,可以使用System.Diagnostics命名空間里的 DebuggerNonUserCodeAttribute屬性,將其應(yīng)用在希望不進(jìn)行VS調(diào)試的代碼段中。
下面舉一個(gè)例子來(lái)說(shuō)明。下面的代碼段中,有兩個(gè)靜態(tài)方法UserCode()和NonUserCode(),其中,在NonUserCode()中,是應(yīng)用了 DebuggerNonUserCode的屬性,這表明這段代碼將在VS調(diào)試運(yùn)行時(shí),VS調(diào)試器不會(huì)進(jìn)入其中。將斷點(diǎn)設(shè)置在其中的第9行,運(yùn)行程序,程序會(huì)在第一個(gè)UserCode()里中斷,現(xiàn)在試著用F11繼續(xù)單步跟蹤,會(huì)發(fā)現(xiàn)系統(tǒng)在進(jìn)入usercode()方法中運(yùn)行后,并沒(méi)有進(jìn)入到NonUserCode ()里運(yùn)行。
- using System;
- using System.Diagnostics;
- class Program
- {
- static void Main(string[] args)
- {
- // Step into F11 from here
- UserCode();// Place break point on this line
- NonUserCode();
- UserCode();
- }
- static void UserCode()
- {
- Console.WriteLine("This is a call from user Code");
- }
- // Attribute to indicate the Debugger to jump
- // over this method
- [DebuggerNonUserCode]
- static void NonUserCode()
- {
- Console.WriteLine("This is a call fron Non User Code");
- }
- }
在Visual Studio 2005中,新引入了"Object Identity While Debugging"的概念,也就是說(shuō),系統(tǒng)給在VS調(diào)試階段的每個(gè)對(duì)象,都可以賦予一個(gè)別名,在VS調(diào)試時(shí),直接引用該別名就可以了。
假設(shè)在VS調(diào)試的時(shí)候,需要跟蹤比如dataset或者h(yuǎn)ashtable等對(duì)象,這些對(duì)象中包含了很多其他的子對(duì)象,如果想對(duì)這些數(shù)量眾多的子對(duì)象進(jìn)行跟蹤的話(huà),將十分麻煩。在Visual Studio 2005中,可以使用object identity(對(duì)象標(biāo)識(shí))的方法去標(biāo)記每一個(gè)對(duì)象。#t#
比如,在一個(gè)windows應(yīng)用程序中,創(chuàng)建了一個(gè)dataset,并將其綁定到datagridview中去。如將sql server 的northwind數(shù)據(jù)庫(kù)中的orders和orderdetail表中的數(shù)據(jù)讀出填充到dataset里去,則在VS調(diào)試時(shí),設(shè)置一個(gè)斷點(diǎn)放在 dataset里填充了數(shù)據(jù)之后的那行,這時(shí),在監(jiān)視窗口中,鼠標(biāo)展開(kāi)this.northwindData這個(gè)dataset,如下圖所示,找到 orders這個(gè)table,然后鼠標(biāo)右鍵,會(huì)彈出一個(gè)菜單,選擇其中的" Make Object ID"。