Cached Property: Easier way?

2020-02-26 14:19发布

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

 private List<Note> notes;
 public List<Note> Notes
    {
        get
        {
            if (this.notes == null)
            {
                this.notes = CalcNotes();
            }
            return this.notes;
        }
    }

I wonder, is there a better way to do this? Is it somehow possible to create a Cached Property or something like that in C#?

7条回答
Root(大扎)
2楼-- · 2020-02-26 14:47

Yes it is possible. The question is, how much you are winning by doing it - you still need the initialization code somewhere, so at most you will be saving the conditional expression.

A while ago I implemented a class to handle this. You can find the code posted in this question, where I ask whether it's a good idea. There are some interesting opinions in the answers, be sure to read them all before deciding to use it.

Edit:

A Lazy<T> class that does basically the same as my implementation that I link to above, has been added to the .NET 4 Framework; so you can use that if you are on .NET 4. See an example here: http://weblogs.asp.net/gunnarpeipman/archive/2009/05/19/net-framework-4-0-using-system-lazy-lt-t-gt.aspx

查看更多
登录 后发表回答