亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

在Framework4.0中實現(xiàn)延遲加載的實現(xiàn)方法

 更新時間:2011年08月17日 16:50:41   作者:  
延遲加載,亦稱延遲實例化,延遲初始化等,主要表達的思想是,把對象的創(chuàng)建將會延遲到使用時創(chuàng)建,而不是在對象實例化時創(chuàng)建對象,即用時才加載。
這種方式有助于提高于應(yīng)用程序的性能,避免浪費計算,節(jié)省內(nèi)存的使用等。針對于這種做法,似乎稱之為即用即創(chuàng)建更為合適些。
先來看一下在Framework4.0中如何實現(xiàn)延遲加載。
Framework4.0提供了一個包裝類 Lazy,可以輕松的實現(xiàn)延遲加載。
復(fù)制代碼 代碼如下:

///這行代碼表明:要創(chuàng)建一個延遲加載的字符串對象s
///原型為LazyT> 對象名=new LazyT>(FunT>)
///采用泛型委托進行構(gòu)造,實例化此委托時要求必須是返回值T類型的方法
///如在本例中,T為string,則TestLazy.GetString方法的返回值必須也是string類型
Lazystring> s = new Lazystring>(TestLazy.GetString);
本例中TestLazy.GetString()方法如下示:
public class TestLazy
{
public static string GetString()
{
return DateTime.Now.ToLongTimeString();
}
}

可以通過IsValueCreated屬性來確定對象是否已創(chuàng)建,通過Value屬性來獲取當(dāng)前對象的值。
Console.WriteLine(s.IsValueCreated);//返回False
Console.WriteLine(s.IsValueCreated);//返回True
下面經(jīng)出完整代碼,以供測試:
復(fù)制代碼 代碼如下:

class Program
{
static void Main(string[] args)
{
///這行代碼表明:要創(chuàng)建一個延遲加載的字符串對象s
///原型為Lazy 對象名=new Lazy(Fun)
///采用泛型委托進行構(gòu)造,實例化此委托時要求必須是返回值T類型的方法
///如在本例中,T為string,則TestLazy.GetString方法的返回值必須也是string類型
Lazy s = new Lazy(TestLazy.GetString);
Console.WriteLine(s.IsValueCreated);//返回False
Console.WriteLine(s.IsValueCreated);//返回True
}
}
public class TestLazy
{
public static string GetString()
{
return DateTime.Now.ToLongTimeString();
}
}

下面再用一個例子,演示延遲加載:
在這個例子中,使用了BlogUser對象,該對象包含多個Article對象,當(dāng)加載BlogUser對象時,Article對象并不加載,當(dāng)需要使用Article對象時,才加載。
復(fù)制代碼 代碼如下:

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-4-20")},
new Article{Id=2,Title="Delegate",PublishDate=DateTime.Parse("2011-4-21")},
new Article{Id=3,Title="Event",PublishDate=DateTime.Parse("2011-4-22")},
new Article{Id=4,Title="Thread",PublishDate=DateTime.Parse("2011-4-23}
};
Console.WriteLine("Article Initalizer");
return articles;
}
}

運行結(jié)果如圖示: 
 
最后說一下,延遲加載主要應(yīng)用場景:

當(dāng)創(chuàng)建一個對象的子對象開銷比較大時,而且有可能在程序中用不到這個子對象,那么可以考慮用延遲加載的方式來創(chuàng)建子對象。另外一種情況就是當(dāng)程序一啟動時,需要創(chuàng)建多個對象,但僅有幾個對象需要立即使用,這樣就可以將一些不必要的初始化工作延遲到使用時,這樣可以非常有效的提高程序的啟動速度。

這種技術(shù)在ORM框架得到了廣泛應(yīng)用,也并非C#獨有的,比如Java里的Hibernate框架也使用了這一技術(shù)。

相關(guān)文章

最新評論