在調試C#代碼時,若是定義了某個屬性獲取對象,以下:this
namespace ConsoleApplication3 { class Program { private static volatile Program _Instance; private static object _thisLock = new object(); public static Program Get { get { lock (_thisLock) { if (_Instance == null) { Console.WriteLine("New Program"); _Instance = new Program(); } return _Instance; } } } public void PrintMsg(string msg) { Console.WriteLine(msg); } static void Main(string[] args) { Program.Get.PrintMsg("Hello"); Console.ReadLine(); } } }
當設置斷點在Program.Get.PrintMsg("Hello");這行時,在變量查看窗口會發現Program.Get具備值,若是此時進入屬性Get中設置斷點,卻發現_Instance不等於null;若是不在Program.Get.PrintMsg("Hello");設置斷點,直接在Get中設置斷點,會發現_Instance確實爲null。一樣的代碼出現兩種不一樣的狀況,_Instance等於null和不等於null的狀況。根據網上的解釋,是由於將斷點設置到Program.Get.PrintMsg("Hello");這行時,在查看變量的過程當中,VS會自動在內部執行屬性代碼,所以當再次進入Get獲取對象時,就會發現對象已經不等於null,所以Program就沒有被指定的代碼new或執行。spa
如何解除這樣的設置?調試
進入菜單 Tools > Options > Debugging > General,取消這個設置:code