缓存的属性:更简单的方法? [英] Cached Property: Easier way?

查看:56
本文介绍了缓存的属性:更简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,其属性的计算成本很高,因此只能在首次访问时进行计算,然后才进行缓存。

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

推荐答案

就语法而言,您可以使用 null-coalescing 运算符,如果您想花哨的话,但不是

As far as syntax goes, you can use the null-coalescing operator if you want to be fancy, but it's not necessarily as readable.

get
{
    return notes ?? (notes = CalcNotes());
}

编辑:更新由Matthew提供。另外,我认为其他答案对于提问者更有用!

这篇关于缓存的属性:更简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆