Implementation of Lazy for .NET 3.5

后端 未结 4 1575
生来不讨喜
生来不讨喜 2020-12-04 16:54

.NET 4.0 has a nice utility class called System.Lazy that does lazy object initialization. I would like to use this class for a 3.5 project. One time I saw an implementation

4条回答
  •  醉话见心
    2020-12-04 17:23

    If you don't need thread-safety, it's pretty easy to put one together with a factory method. I use one very similar to the following:

    public class Lazy
    {
        private readonly Func initializer;
        private bool isValueCreated;
        private T value;
    
        public Lazy(Func initializer)
        {
            if (initializer == null)
                throw new ArgumentNullException("initializer");
            this.initializer = initializer;
        }
    
        public bool IsValueCreated
        {
            get { return isValueCreated; }
        }
    
        public T Value
        {
            get
            {
                if (!isValueCreated)
                {
                    value = initializer();
                    isValueCreated = true;
                }
                return value;
            }
        }
    }
    

提交回复
热议问题