31

我想使用Lazy T来实现记忆,但初始化函数似乎需要静态上下文。

例如,以下代码拒绝编译,警告非静态成员ab不可访问。我不清楚为什么会这样,因为Lazy对象本身就是一个实例成员,并且在静态上下文中没有可见性。

public class SomeExpensiveCalculation
{
    private int a;
    private int b;
    public Lazy<int> Result = new Lazy<int>(() => a + b); //nope!
}
4

3 回答 3

34

构造函数(或方法)之外的对象初始化器只能引用静态成员。这是因为实例在构造函数运行之前还没有被构造,因此这些字段还没有“准备好”,因此不能被引用。静态字段之所以有效,是因为它们在字段之前初始化。

请注意,错误不是由 引起的Lazy<T>,而是由 lambda 表达式引起的。解决方法(以及这样做的正确方法)是Result在构造函数中进行初始化。

于 2011-07-14T07:44:23.313 回答
12

I don´t know why your code does not work, but this should work:

    public class SomeExpensiveCalculation
    {
        private int a;
        private int b;
        public Lazy<int> Result;
        public SomeExpensiveCalculation()
        {
             Result = new Lazy<int>(() => a + b);
        }
    }
于 2011-07-14T07:38:58.213 回答
1

Just to expand on @Ondra's answer, this can be used with an injected factory as well. One caveat - be wary of the relative lifespans of the lazy and the factory:

public class SomeClass
{
  private readonly Lazy<ISomeDependency> _lazyField;

  // Ctor
  public SomeClass(ISomeFactory factory)
  {
     _lazyField = new Lazy<ISomeDependency>(() => factory.Create());
  }
}
于 2013-10-16T09:00:12.103 回答