为什么Lazy <t>不懒惰?

时间:2017-08-01 17:36:55

标签: c# lazy-initialization

我有几个使用Entity Framework的简单数据库查询,我希望使用Lazy<T>加载一次,但我可以看到每次调用属性时都会执行查询。我尝试的变化是:

public static IEnumerable<string> Foos => new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name)).Value;

public static IEnumerable<string> Foos=> new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray()).Value;

public static Lazy<IEnumerable<string>> Foos => new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray());

public static IEnumerable<string> LightingEnvironments
{
    get
    {
        var lazy = new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray());
        return lazy.Value;
    }
}

1 个答案:

答案 0 :(得分:9)

每次调用属性getter时,您都在构建一个新的Lazy。如果您保留Lazy实例并在其上调用Lazy属性,则Value仅允许您重新使用已构造的值每次需要值时都会Lazy实例