Cached Property: Easier way?

前端 未结 7 2038
傲寒
傲寒 2021-01-01 10:00

I have a object with properties that are expensive to compute, so they are only calculated on first access and then cached.

 private List notes;
         


        
7条回答
  •  庸人自扰
    2021-01-01 10:47

    In .NET 3.5 or earlier, what you have is a very standard practice, and a fine model.

    (Although, I would suggest returning IList, or IEnumerable if possible, instead of List in your public API - List should be an implementation detail...)

    In .NET 4, however, there is a simpler option here: Lazy. This lets you do:

    private Lazy> notes;
    public IEnumerable Notes
    {
        get
        {
            return this.notes.Value;
        }
    }
    
    // In constructor:
    this.notes = new Lazy>(this.CalcNotes);
    

提交回复
热议问题