C#基础概念之延迟加载
%3Cp%3E
延迟加载,亦称延迟实例化,延迟初始化等,主要表达的思想是,把对象的创建将会延迟到使用时创建,而不是在对象实例化时创建对象,即用时才加载。这类方式有助于进步于利用程序的性能,避免浪费计算,节省内存的使用等。针对这类做法,仿佛称之为即用即创建更加合适些。
先来看1下在Framework4.0中如何实现延迟加载。
Framework4.0提供了1个包装类 Lazy,可以轻松的实现延迟加载。
-
-
-
-
- Lazystring> s = new Lazystring>(TestLazy.GetString);
|
本例中TestLazy.GetString()方法以下示:
- public class TestLazy
- {
- public static string GetString()
- {
- return DateTime.Now.ToLongTimeString();
- }
- }
|
可以通过IsValueCreated属性来肯定对象是否是已创建,通过Value属性来获得当前对象的值。
- Console.WriteLine(s.IsValueCreated);
- Console.WriteLine(s.IsValueCreated);
|
下面经出完全代码,以供测试:
- class Program
- {
- static void Main(string[] args)
- {
-
-
-
-
- Lazy s = new Lazy(TestLazy.GetString);
- Console.WriteLine(s.IsValueCreated);
- Console.WriteLine(s.IsValueCreated);
- }
- }
- public class TestLazy
- {
- public static string GetString()
- {
- return DateTime.Now.ToLongTimeString();
- }
- }
|
下面再用1个例子,演示延迟加载:
在这个例子中,使用了BlogUser对象,该对象包括多个Article对象,当加载BlogUser对象时,Article对象其实不加载,当需要使用Article对象时,才加载。
- class Program
- {
- static void Main(string[] args)
- {
- BlogUser blogUser = new BlogUser(1);
- Console.WriteLine("blogUser has been initialized");
- {
- Console.WriteLine(article.Title);}
- }
- }
- public class BlogUser
- {
- public int Id { get; private set; }
- public Lazy> Articles { get; private set; }
- public BlogUser(int id)
- {
- this.Id = id;
- Articles =new Lazy>(()=>ArticleServices.GetArticesByID(id));
- Console.WriteLine("BlogUser Initializer");
- }
- }
- public class Article
- {
- public int Id { get; set; }
- public string Title{get;set;}
- public DateTime PublishDate { get; set;}
- public class ArticleServices
- {
- public static List GetArticesByID(int blogUserID)
- {
- List articles = new List {
- new Article{Id=1,Title="Lazy Load",PublishDate=DateTime.Parse("2011⑷⑵0")},
- new Article{Id=2,Title="Delegate",PublishDate=DateTime.Parse("2011⑷⑵1")},
- new Article{Id=3,Title="Event",PublishDate=DateTime.Parse("2011⑷⑵2")},
- new Article{Id=4,Title="Thread",PublishDate=DateTime.Parse("2011⑷⑵3}
- };
- Console.WriteLine("Article Initalizer");
- return articles;
- }
- }
|
运行结果如图示:

最后说1下,延迟加载主要利用处景:
当创建1个对象的子对象开消比较大时,而且有可能在程序中用不到这个子对象,那末可以考虑用延迟加载的方式来创建子对象。另外1种情况就是当程序1启动时,需要创建多个对象,但唯一几个对象需要立即使用,这样便可以够将1些没必要要的初始化工作延迟到使用时,这样可以非常有效的进步程序的启动速度。
这类技术在ORM框架得到了广泛利用,也并非C#独占的,比如Java里的Hibernate框架也使用了这1技术。
http://www.fw8.net/%3C%2Fp%3E
TAG:
方法,
实例,
对象,
类型,
加载