In the program, sometimes we have a new object, but it is not used immediately. This wastes memory resources and can use the lazy class provided by. Net for us.
1 using system;
2 using system. Collections. Generic;
3 using system. LINQ;
4 using system. text;
5 using system. Threading;
6
7 namespace lazy
8 {
9 class Program
10 {
11 static void main (string [] ARGs)
12 {
13 // use lazy
14 lazy <person> person = new lazy <person> ();
15 datetime dt1 = datetime. now;
16 // print the current time
17 console. writeline (dt1 );
18 // The main thread sleeps for 5 seconds
19 thread. Sleep (1000*5 );
20 // print the time in the person class (this time is the value assigned when the constructor is called)
21 Console. WriteLine (person. Value. DT );
22
23 Console. ReadKey ();
24}
25}
26 class Person
27 {
28 private DateTime dt;
29 // Constructor
30 public Person ()
31 {
32 DT = DateTime. Now;
33}
34 public DateTime DT
35 {
36 get {return dt ;}
37 set {dt = value ;}
38}
39}
40}
The output result is as follows:
It can be seen that when we execute Lazy <Person> person = newLazy <Person> ();, the person object is not created, but the Console is executed. writeLine (person. value. (DT); create an object.
Below we simulate the implementation of the Lazy class:
1 class Program
2 {
3 static void Main (string [] args)
4 {
5 // The MyLazy constructor is called here.
6 // The Person constructor is called only when Value is used.
7 // the actual application only consumes a lot of memory resources.
8 // or other unmanaged resource classes are worth using Lazy <T>
9 MyLazy <Person> person = new MyLazy <Person> ();
10 DateTime dt1 = DateTime. Now;
11 // print the current time
12 Console. WriteLine (dt1 );
13 // The main thread sleeps for 5 seconds
14 Thread. Sleep (1000*5 );
15 // print the time in the Person class (this time is the value assigned when the constructor is called)
16 Console. WriteLine (person. Value. DT );
17
18 Console. ReadKey ();
19}
20}
21
22 // your own lazy class
23 class mylazy <t> where T: New ()
24 {
25 private t instance;
26
27 public T value
28 {
29 get
30 {
31 // determine whether an instance is created
32 If (instance = NULL)
33 {
34 // if no instance is created, create the instance first.
35 instance = new T ();
36}
37 return instance;
38}
39}
40}
41
42 class person
43 {
44 private datetime DT;
45 // Constructor
46 Public Person ()
47 {
48 DT = DateTime. Now;
49}
50 public DateTime DT
51 {
52 get {return dt ;}
53 set {dt = value ;}
54}
55}