C# Lazy Loaded Automatic Properties

前端 未结 12 2138
执笔经年
执笔经年 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 11:50

    Here's my implementation of a solve to your problem. Basically the idea is a property that will be set by a function at first access and subsequent accesses will yield the same return value as the first.

    public class LazyProperty
    {
        bool _initialized = false;
        T _result;
    
        public T Value(Func fn)
        {
            if (!_initialized)
            {
                _result = fn();
                _initialized = true;
            }
            return _result;
        }
     }
    

    Then to use:

    LazyProperty _eyeColor = new LazyProperty();
    public Color EyeColor
    { 
        get 
        {
            return _eyeColor.Value(() => SomeCPUHungryMethod());
        } 
    }
    

    There is of course the overhead of passing the function pointer around, but it does the job for me and I don't notice too much overhead compared to running the method over and over again.

提交回复
热议问题