代码之家  ›  专栏  ›  技术社区  ›  DarthVader

数据访问的延迟初始化

  •  0
  • DarthVader  · 技术社区  · 16 年前

    我正在访问数据库以批量填充字段。

    PopulateAobjs();
    PopulateBobjs();
    PopulateCobjs();
    ...
    

    一旦值被填充,我将实体存储在 Dictionary<Id, Entity> .

    如果我不需要的话,我想让这个过程变懒 C 对象,则不需要调用该方法。等。

    怎么能做到?

    懒散;?

    2 回复  |  直到 16 年前
        1
  •  2
  •   herzmeister    16 年前

    与其执行这样的初始化例程,不如使用延迟加载属性来执行这样的操作。

    private Lazy<IEnumerable<CObject>> cObjects = new Lazy<IEnumerable<CObject>>(LoadCObjects);
    
    public IEnumerable<CObject> CObjects
    {
        get { return this.cObjects.Value; }
    }
    

    CObjects 将在任何人第一次访问该属性时加载。

    编辑:当你不在.NET 4.0中时, Lazy<T> 是一种很好的方式:

    private IEnumerable<CObject> cObjects;
    
    public IEnumerable<CObject> CObjects
    {
        get
        {
            if (this.cObjects == null)
                lock (this.someLockObject)
                    if (this.cObjects == null)
                        this.cObjects = this.LoadCObjects();
    
            return this.cObjects;
        }
    }
    
        2
  •  0
  •   Jonathan Allen    16 年前

    为此,我通常在get属性方法中有加载集合的代码。根据类的不同,它要么直接加载数据,要么请求全局缓存加载数据。

    Property FooCustomers
        Get
           If _Customers IS NULL THEN Then _Customers = CustomerCache.FindByKey(companyKeys)
            Return _Customers
    
    推荐文章