1

我想制作一个可以通过属性注入进行测试的惰性属性。如果我要使用 Lazy 字段,我看不出如何在测试期间注入自己的字段。这是我的代码:

private IExpensive expensive;
private bool expensiveInitialized;
private object expensiveLockingObject = new object();

public IExpensive Expensive
{
   get
   {
      LazyInitializer.EnsureInitialized(ref expensive, ref expensiveInitialized, ref expensiveLockingObject,
         () => new Expensive(myStaticArg1, myStaticArg2, ...));

      return expensive;
   }
   internal protected set
   {
      expensiveInitialized = true;
      expensive = value;
   }
}

我想知道 BCL 团队是否承诺此代码是线程安全的?从文档中不清楚。

4

1 回答 1

2

从文档链接:

LazyInitializer 的方法是线程安全的,可以同时从多个线程调用。

于 2011-05-12T20:05:05.923 回答