. NET generic 04, using Lazy & lt; T & gt; for delayed loading,. netlazy

Source: Internet
Author: User

. NET generic 04, use Lazy <T> to implement delayed loading,. netlazy

For the creation of some "large objects", we often want to delay loading, that is, to create an object instance when necessary. Now Lazy <T> supports this feature well. It mainly includes:

 

  • Before Lazy <T>
  • Lazy <T> instance
  • Essence of delayed Loading

 

Before Lazy <T>

Before Lazy <T> is available, we use the following method to implement delayed loading.

public class LazySinleton
{
    private LazySingleton()
    {}
 
    public static LazySingleton Instance
    {
        get
        {
            return Lazy.data;
        }
    }
 
    private class Lazy
    {
        static Lazy()
        {}
 
        internal static readonly LazySingleton data = new LazySingleton();
    }
}
 

Above
● Private constructor shields the LazySingleton class from being created by Constructor
● The data field of the private nested class Lazy is responsible for providing a LazySingleton instance.
● The Instance represented by the internal class Lazy. data can be obtained only through the attribute Instance of LazySingleton.

 

Lazy <T> instance

Let's first look at the definition of Lazy <T>:

public class Lazy<T>{    public Lazy();    public Lazy(bool isThreadSafe);    public Lazy(Func<T> valueFactory);    public Lazy(LazyThreadSafeMode mode);    public Lazy(Func<T> valueFactory, bool isThreadSafe);    public Lazy(Funct<T> valueFactory, LazyThreadSafetyMode mode);    public bool IsValueCreated{get;}    public T Value {get;}    public override string ToStirng();}

 

You can use the constructors of Lazy <T> to create an object by reloading the Value attribute of delayed loading and obtain the object instance.

public class SomeClass{    public int ID{get;set;}}Lazy<SomeClass> temp = new Lazy<SomeClass>();Console.WriteLine(temp.Value.ID);

 

The above only applies to situations where no constructor is available. How can we deal with constructor?
-- Use public Lazy (Func <T> valueFactory) to create an object through delegation

pubic class SomeClass{    public int ID{get;set;}    public SomeClass(int id)    {        this.ID = id;    }}Lazy<SomeClass> temp = new Lazy<SomeClass>(() => new Big(100));Console.WriteLine(temp.Value.ID);

 

Essence of delayed Loading

Creates a custom delayed loading class.

Public class MyLazy <T> {private volatile object boxed; // volatile indicates that the private Func <T> valueFactory field can be modified in the case of multithreading; // delegate, used to produce T object instance static MyLazy () {} public MyLazy (Func <T> valueFactory) {this. valueFactory = valueFactory;} public T Value {get {Boxed boxed = null; if (this. boxed! = Null) {boxed = this. boxed as Boxed; if (boxed! = Null) {return boxed. value ;}} return this. init () ;}// initialize the object instance private T Init () {Boxed boxed = null; if (this. boxed = null) {boxed = this. createValue (); this. boxed = boxed;} return boxed. value;} // create an internal class instance private Boxed CreateValue () {// if the principal valueFactory of the object instance to be created exists if (this. valueFactory! = Null) {// generate the object instance return new Boxed (this. valueFactory ();} else {// otherwise, an object instance return new Boxed (T) Activator is generated through reflection. createInstance (typeof (T);} // internal nested class, which is assigned a private class Boxed {internal T value; internal Boxed (T value) value through the constructor) {this. value = value ;}}}

 

Custom class with constructor.

public class Big    {        public int ID { get; set; }        public Big(int id)        {            this.ID = id;        }    }

 

Customize the factory class for creating object instances.

public class BigFactory    {        public static Big Build()        {            return new Big(10);        }    }


Client call.

class Program    {        static void Main(string[] args)        {            MyLazy<Big> temp = new MyLazy<Big>(() => BigFactory.Build());            Console.WriteLine(temp.Value.ID);            Console.ReadKey();        }    }

 

The essence of delayed loading is:

● Object instances are generated by Nested classes of delayed loading classes.
● A delayed loading class attribute is used to obtain the object instance, and the object instance is created by delegation.

 

References:
NET (version 2nd), Author: Wang Tao.

 

". NET generic" series include:

. NET generic 01. Why does it need generic and basic syntax. NET generic 02, generic use. NET generic 03, generic type conversion, covariant, and inverter. NET generic 04, use Lazy <T> to implement delayed Loading
C # generic List <T>

When creating a list class, the Data Type of the list item may be int, string, or other types, but no matter what type, if the processing method for the List class is the same, there is no need to specify the Data Type in advance, and it is left to be specified when the list class is instantiated. This is equivalent to taking the data type as a parameter, which can reuse code to the maximum extent, protect the type security and improve performance. Generic type introduces the concept of type parameter to. NET Framework. T is usually used as a generic type parameter.
ArrayList is a non-generic collection class. Any reference or value type added to ArrayList is implicitly forcibly converted to an Object. If the item is of the value type, you must bind it to the list and unpack it during retrieval. Another restriction is the lack of type check during compilation. Because ArrayList forcibly converts all items to objects, it cannot prevent the client code from adding both the int and string types during compilation, compilation can also be passed, and errors can not be detected until the runtime.
The most common use of generics is to create a collection class .. The. NET Framework class library contains several Generic collection classes in the Collections. Generic namespace. The List <T> class is the generic equivalent class of the ArrayList class. The IList generic interface is implemented using an array of sizes that can be dynamically increased as needed. The advantage of dynamic arrays is that you do not need to set a large array in advance to reduce unnecessary memory overhead.
The C # programming guide of Microsoft MSDN recommends that you use generic collection classes, such as the List <T> class, instead of non-generic collection classes, such as the ArrayList class, and do not create a collection class on your own. The reason is that you do not have to do the work that the. NET Framework has completed. The Common Language Runtime Library can share the Microsoft intermediate language code and element data, which cannot be achieved by self-compiled strong types.
The following example illustrates the usage of List <T>.
Public class Student // The Student class acts as the data source
{
Public string Name {get; set ;}
Public List <int> Scores {get; set;} // score set
}
Static void Main (string [] args)
{
// Initialize the generic List <Student>. The element in the set contains an internal List of scores <int>
List <Student> students = new List <Student> ();
Students. Add (new Student {Name = "Zhang San", Scores = new List <int> {93, 72, 88, 78 }});
Students. Add (new Student {Name = "", Scores = new List <int> {95, 71, 88, 68 }});
// Query by using Linq
Var Query = from student in students
Where student. Scores. Average ()> = 80
Select new
{
Name = student. Name,
Score = student. SC ...... remaining full text>

C # net framework 11

. Net framework 1.1 does not support generics. It is useless even if you take the 2.0 code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.