C#之消極式載入

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   使用   java   for   

消極式載入,亦稱延遲執行個體化,延遲初始化等,主要表達的思想是,把對象的建立將會延遲到使用時建立,而不是在對象執行個體化時建立對象,即用時才載入。這種方式有助於提高於應用程式的效能,避免浪費計算,節省記憶體的使用等。針對於這種做法,似乎稱之為即用即建立更為合適些。

先來看一下在Framework4.0中如何?消極式載入。

Framework4.0提供了一個封裝類 Lazy<T>,可以輕鬆的實現消極式載入。

///這行代碼錶明:要建立一個消極式載入的字串對象s            ///原型為Lazy<T> 對象名=new Lazy<T>(Fun<T>)            ///採用泛型委派進行構造,執行個體化此委託時要求必須是傳回值T類型的方法            ///如在本例中,T為string,則TestLazy.GetString方法的傳回值必須也是string類型            Lazy<string> s = new Lazy<string>(TestLazy.GetString);

本例中TestLazy.GetString()方法如下示:

public class TestLazy    {         public static string GetString()        {            return DateTime.Now.ToLongTimeString();        }    }

可以通過IsValueCreated屬性來確定對象是否已建立,通過Value屬性來擷取當前對象的值。

字串對象消極式載入完整樣本    class Program    {        static void Main(string[] args)        {                            ///這行代碼錶明:要建立一個消極式載入的字串對象s            ///原型為Lazy<T> 對象名=new Lazy<T>(Fun<T>)            ///採用泛型委派進行構造,執行個體化此委託時要求必須是傳回值T類型的方法            ///如在本例中,T為string,則TestLazy.GetString方法的傳回值必須也是string類型            Lazy<string> s = new Lazy<string>(TestLazy.GetString);            Console.WriteLine(s.IsValueCreated);//返回False            Console.WriteLine(s.Value); //返回S的當前值            Console.WriteLine(s.IsValueCreated);//返回True           }    }    public class TestLazy    {         public static string GetString()        {            return DateTime.Now.ToLongTimeString();        }    }

下面再用一個例子,示範消極式載入。

在這個例子中,使用了BlogUser對象,該對象包含多個Article對象,當載入BlogUser對象時,Article對象並不載入,當需要使用Article對象時,才載入。

包含子物件的消極式載入    class Program    {        static void Main(string[] args)        {            BlogUser blogUser = new BlogUser(1);            Console.WriteLine("blogUser has been initialized");            foreach (var article in blogUser.Articles.Value)            {                Console.WriteLine(article.Title);            }                         }    }        public class BlogUser    {        public int Id { get; private set; }                public Lazy<List<Article>> Articles { get; private set; }        public BlogUser(int id)        {            this.Id = id;            Articles =new Lazy<List<Article>>(()=>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<Article> GetArticesByID(int blogUserID)        {            List<Article> articles = new List<Article> {                            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;        }    }

運行結果示:

 

最後說一下,消極式載入主要應用情境

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

這種技術在ORM架構得到了廣泛應用,也並非C#專屬的,比如Java裡的Hibernate架構也使用了這一技術。

C#之消極式載入

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.