我有一个购物车模型类,它有一个 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/