Cached Property: Easier way?

前端 未结 7 2068
傲寒
傲寒 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:38

    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 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

提交回复
热议问题