C# 4 延迟加载和延迟<T>

标签 c# .net c#-4.0 lazy-loading

我有一个购物车模型类,它有一个 List 属性,如下所示:

public List<CartItem> CartItems
{
    get
    {
        if (_cartItems == null)
            _cartItems = Services.CartItemService.GetCartItems();

        return _cartItems;
    }
}
private List<CartItem> _cartItems;

这很好,除非用于从 SQL Server 查询数据的服务返回 null,在这种情况下,数据库可能会在引用 CartItems 时被多次不必要地命中。然后我注意到 Lazy<T> 对我可用,所以我尝试稍微修改我的代码(因为 Lazy<T> 帐户为 null 并且会阻止对数据库的多次点击)
public List<CartItem> CartItems
{
    get
    {
        return _cartItems.Value;
    }
}

private Lazy<List<CartItem>> _cartItems = new Lazy<List<CartItem>>(() =>
{
    // return Services.CartItemService.GetCartItems(); cannot be called here :(
});

编译时错误是

"A field initializer cannot reference the non-static field, method, or property"



Services 是与 CartItems 同一个类中的公共(public)属性,但我不知道是否可以在 Func<List<CartItem>> 委托(delegate)中访问它。我不想为每个属性创建工厂类 - 我在很多地方都必须给我们这样的东西,而且我想要......好吧......懒惰。

最佳答案

您可以在构造函数中创建该字段。
将服务调用移动到它自己的方法也可能是值得的。
IE。

private readonly Lazy<List<CartItem>> _cartItems;

public MyClass()
{
    _cartItems = new Lazy<List<CartItem>>(GetCartItems);
}

public List<CartItem> GetCartItems()
{
    return Services.CartItemService.GetCartItems();
}

关于C# 4 延迟加载和延迟<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7917393/

相关文章:

c# - ImmutableArray<T> 和 ImmutableList<T> 的区别

windows - 你如何自动调整winform?

c# - Winforms : Intercepting Mouse Event on Main Form first, 不在控件上

c# - 从json字符串读取数据到c#对象

.net - WCF 客户端-服务器同步 : Polling vs. 绑定(bind)

c# - 使用泛型类型 'System.Collections.Generic.List' 需要 '1' 类型参数

c# - Silverlight:值不在预期范围异常之内

c# - 没有科学记数法的 double 字符串转换

c# - 从 List 转换为 IEnumerable 格式

c# - 为什么 HttpWebRequest.BeginGetResponse() 同步完成?