The object creation way, has always represented the software industry productivity direction, has represented the advanced software technology development direction, also represents the vast majority of program developer's collective intelligence. Created in new ways, through factory methods, and using IOC containers, the creation of live instance members is achieved in different ways. And this article is concerned about the lazy<t> also do this thing. But, simply put,,lazy<t> is created on demand, not on time.
 
We often have this situation, the creation of an associated object requires a lot of overhead, and in order to avoid creating such a guy at every run, there is a clever way to implement lazy objects, or to delay loading. before. NET 4.0, the mechanism for implementing lazily objects needs to be implemented and managed by the developer themselves, for example, You can turn to Comrade Zhao's more ideal delay agent to write a text to understand its principles and occasions. Thankfully, another fun guy in. NET 4.0 is system.lazy<t>. It is defined as follows:
 
[Serializable]
 public class Lazy<T>
 {
    public Lazy();
    public Lazy(bool isThreadSafe);
    public Lazy(Func<T> valueFactory);
    public Lazy(Func<T> valueFactory, bool isThreadSafe);
 
    public bool IsValueCreated { get; }
    public T Value { get; }
 
    public override string ToString();
 }
 
 注:VS2010 Beta2对Lazy<T>和VS2010 Beta1有较大差异,因此本文仅以最新版本为标准,并不保证最终.NET 4.0正式版的实际情况。
 
Let's say we have a big guy:
 
public class Big
 {
    public int ID { get; set; }
 
    // Other resources
 }
 
Then, you can implement the deferred creation of big in the following ways:
 
static void Main(string[] args)
 {
    Lazy<Big> lazyBig = new Lazy<Big>();
 }
 
From the definition of lazy<t>, the Value property is the real big object that we wrap in lazy wrapper, then when we first visit Lazybig.value, we automatically create the big instance.
 
static void Main(string[] args)
 {
    Lazy<Big> lazyBig = new Lazy<Big>();
 
    Console.WriteLine(lazyBig.Value.ID);
 }
 
Of course, there is a definition that lazy is far from being so childish, it can also provide us with the following services:
 
By isvaluecreated, gets whether the instance object has been created.
 
Resolves a non-default constructor problem.
 
Obvious. Our big class does not provide a parameter constructor, so the following big class:
 
public class Big
 {
    public Big(int id)
    {
      this.ID = id;
    }
 
    public int ID { get; set; }
 
    // Other resources
 }