Implementation of Lazy for .NET 3.5

后端 未结 4 1569
生来不讨喜
生来不讨喜 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:20

    A somewhat simplify version of aaron's

    public class Lazy where T : new()
    { 
      private T value; 
    
      public bool IsValueCreated { get; private set;}
    
      public T Value 
      { 
        get 
        { 
            if (!IsValueCreated) 
            { 
                value = new T();
                IsValueCreated = true; 
            } 
            return value; 
        } 
      } 
    } 
    

提交回复
热议问题