我想知道 Lazy<T> 的两个构造函数重载之间有什么区别?类。
Lazy(Func, Boolean) - Initializes a new instance of the Lazy class. When lazy initialization occurs, the specified initialization function and initialization mode are used.
Lazy(Func, LazyThreadSafetyMode) - Initializes a new instance of the Lazy class that uses the specified initialization function and thread-safety mode.
从线程安全的角度来看,第二个构造函数是否更灵活?哪个LazyThreadSafetyMode member 是 Lazy<...>(..., true) 的类似物?
请您参考如下方法:
来自反射器:
public Lazy(Func<T> valueFactory, bool isThreadSafe) : this(valueFactory, isThreadSafe ?LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
{
}
因此,如果您传递 true,它将转换为 LazyThreadSafetyMode.ExecutionAndPublication。
false 将转换为 LazyThreadSafetyMode.None
顺便说一句,如果您只传递值因子(完全省略 bool),它会使用 LazyThreadSafetyMode.ExecutionAndPublication。
