Cached Property: Easier way?

前端 未结 7 2026
傲寒
傲寒 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:30

    If the value is non-trivial to compute, I generally prefer using a method (GetNotes()). There's nothing stopping you from caching the value with a method, plus you can add the [Pure] attribute (.NET 4) if applicable to indicate the method does not alter the state of the object.

    If you do decide to stay with the following, I recommend:

    Whenever you have a lazily-evaluated property, you should add the following attribute to ensure that running in the debugger behaves the same as running outside of it:

    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    

    Also, starting with .NET 4, you can use the following:

    // the actual assignment will go in the constructor.
    private readonly Lazy> _notes = new Lazy>(CalcNotes);
    
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public List Notes
    {
        get { return _notes.Value; }
    }
    

提交回复
热议问题