C#在调试时避免触发属性

在调试C#代码时,如果定义了某个属性获取对象,如下:

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或执行。

如何解除这样的设置?

进入菜单 Tools > Options > Debugging > General,取消这个设置:

猜你喜欢

转载自my.oschina.net/u/3489228/blog/1938761