C# Lazy Loaded Automatic Properties

前端 未结 12 2184
执笔经年
执笔经年 2020-12-04 11:08

In C#,

Is there a way to turn an automatic property into a lazy loaded automatic property with a specified default value?

Essentially, I am trying to turn th

12条回答
  •  执念已碎
    2020-12-04 12:03

    I did it like this:

    public static class LazyCachableGetter
    {
        private static ConditionalWeakTable> Instances = new ConditionalWeakTable>();
        public static R LazyValue(this T obj, Func factory, [CallerMemberName] string prop = "")
        {
            R result = default(R);
            if (!ReferenceEquals(obj, null))
            {
                if (!Instances.TryGetValue(obj, out var cache))
                {
                    cache = new ConcurrentDictionary();
                    Instances.Add(obj, cache);
    
                }
    
    
                if (!cache.TryGetValue(prop, out var cached))
                {
                    cache[prop] = (result = factory());
                }
                else
                {
                    result = (R)cached;
                }
    
            }
            return result;
        }
    }
    

    and later you can use it like

           public virtual bool SomeProperty => this.LazyValue(() =>
        {
            return true; 
        });
    

提交回复
热议问题