在程序中,有时候我们new了一个对象,但是并没有立即用到它,这样浪费了内存资源,可以用.net为我们提供的Lazy类。

 

 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 //使用Lazy
14 Lazy<Person> person = new Lazy<Person>();
15 DateTime dt1 = DateTime.Now;
16 //打印当前时间
17 Console.WriteLine(dt1);
18 //主线程 睡5秒
19 Thread.Sleep(1000 * 5);
20 //打印Person类中的时间(这个时间是调用构造函数时赋的值)
21 Console.WriteLine(person.Value.DT);
22
23 Console.ReadKey();
24 }
25 }
26 class Person
27 {
28 private DateTime dt;
29 //构造函数
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 }



输出结果如下图:

 

可见,当我们执行Lazy<Person> person = newLazy<Person>();时并没有创建person对象,而是等到执行Console.WriteLine(person.Value.DT);时才创建对象。

 

 

下面我们模拟实现一下Lazy类:

 1 class Program
2 {
3 static void Main(string[] args)
4 {
5 //这里调用的是MyLazy的构造函数
6 //只有使用Value的时候调用的才是Person的构造函数
7 //实际应用时只有非常消耗内存资源
8 //或者其他非托管资源的类才值得用Lazy<T>
9 MyLazy<Person> person = new MyLazy<Person>();
10 DateTime dt1 = DateTime.Now;
11 //打印当前时间
12 Console.WriteLine(dt1);
13 //主线程 睡5秒
14 Thread.Sleep(1000 * 5);
15 //打印Person类中的时间(这个时间是调用构造函数时赋的值)
16 Console.WriteLine(person.Value.DT);
17
18 Console.ReadKey();
19 }
20 }
21
22 //自己的Lazy类
23 class MyLazy<T> where T:new()
24 {
25 private T instance;
26
27 public T Value
28 {
29 get
30 {
31 //判断实例是否创建
32 if (instance == null)
33 {
34 //如果没创建,则先创建实例
35 instance = new T();
36 }
37 return instance;
38 }
39 }
40 }
41
42 class Person
43 {
44 private DateTime dt;
45 //构造函数
46 public Person()
47 {
48 DT = DateTime.Now;
49 }
50 public DateTime DT
51 {
52 get { return dt; }
53 set { dt = value; }
54 }
55 }



 

 



posted on 2012-02-28 18:38  什么玩  阅读(227)  评论(0编辑  收藏  举报