在.NET4.0中,可以使用Lazy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Student
{
public Student()
{
this.Name = "DefaultName";
this.Age = 0;
Console.WriteLine("Student is init...");
}
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Lazy<Student> stu = new Lazy<Student>();
if (!stu.IsValueCreated)
{
Console.WriteLine("Student isn't init!");
}
Console.WriteLine(stu.Value.Name);
stu.Value.Name = "Tom";
stu.Value.Age = 21;
Console.WriteLine(stu.Value.Name);
Console.Read();
}
}
Output:
1
2
3
4
Student isn't init!
Student is init...
DefaultName
Tom
可以看到,Student是在输出Name属性时才进行初始化的,也就是在第一次使用时才实例化,这样就可以减少不必要的开销。
Lazy