我有一个单例类,它在第一次调用属性时延迟创建它的实例(属性副作用)。
namespace singletontest2
{
using System.Diagnostics;
using MySingleton = Singleton<MyClass>;
public class MyClass
{
private int val = 42;
public MyClass()
{
}
}
public static class Singleton<T> where T : new()
{
private static T t;
public static bool IsNull
{
get
{
return t == null;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static T Instance
{
get
{
if (t == null)
t = new T();
return t;
}
}
}
class Program
{
static void Main(string[] args)
{
var a = MySingleton.IsNull;
var d = MySingleton.Instance;
}
}
}
如果我在 Instance
中放置一个断点属性(property) setter/getter 和 var d
线,t
当我进入 Instance
时,成员已经被初始化 setter/getter 。
如果我从 var d
移动断点到下一行,t
当我调试到 Instance
时为空 setter/getter 。
我的印象是DebuggerBrowsable
属性会阻止这种情况,但似乎没有任何区别。
但是,如果我消除 using MySingleton = Singleton<MyClass>;
以上并调用Singleton<MyClass>.Instance;
而不是 MySingleton.Instance;
, 然后是成员 t
当我输入 Instance
时为空 setter/getter 不管DebuggerBrowsable
这就是我想要的。
为什么是using
允许调试器在代码实际执行之前评估该属性的指令?
最佳答案
关闭工具->选项->调试->启用属性评估和其他隐式函数调用,如此处所提倡:https://msdn.microsoft.com/en-us/library/0taedcee.aspx
关于c# - 如何防止 Visual Studio 2015 的调试器评估具有副作用的静态属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45828737/