在调试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