C#對(duì)象集合初始化器淺談
C#語(yǔ)言還是比較常見(jiàn)的東西,這里我們主要介紹C#對(duì)象集合初始化器,包括介紹編譯器自動(dòng)的調(diào)用了List的無(wú)參構(gòu)造方法等方面。
在寫(xiě)一些實(shí)體類(lèi)的時(shí)候,我們往往在寫(xiě)構(gòu)造方法的時(shí)候思考很長(zhǎng)時(shí)間,除了一個(gè)無(wú)參構(gòu)造器外還在想需要寫(xiě)幾個(gè)構(gòu)造器呢?哪些參數(shù)是需要初始化的?,F(xiàn)在你再也不需要為這事煩惱了。C# 3.0為你提供了C#對(duì)象集合初始化器:
- public class Book
- {
- ///
- /// 圖書(shū)名稱(chēng)
- ///
- public string Title { get; set; }
- ///
- /// 單價(jià)
- ///
- public float Price { get; set; }
- ///
- /// 作者
- ///
- public string Author { get; set; }
- ///
- /// ISBN號(hào)
- ///
- public string ISBN { get; set; }
- }
- //對(duì)象初始化器
- Book book = new Book { Title="Inside COM",ISBN="123-456-789"};
現(xiàn)在你想初始化幾個(gè)就初始化幾個(gè),不需要出現(xiàn)這種情況:
- public Book():this("")
- {
- }
- public Book(string title):this(title,0)
- {
- }
- public Book(string title, float price):this(title,price,"")
- {
- }
- public Book(string title, float price, string isbn)
- {
- this.Title = title;
- this.Price = price;
- this.ISBN = isbn;
- }
- List<Book> <>g__initLocal0 = new List<Book>();
- Book <>g__initLocal1 = new Book();
- <>g__initLocal1.Title = "Inside COM";
- <>g__initLocal1.ISBN = "123-456-789";
- <>g__initLocal1.Price = 20f;
- <>g__initLocal0.Add(<>g__initLocal1);
- Book <>g__initLocal2 = new Book();
- <>g__initLocal2.Title = "Inside C#";
- <>g__initLocal2.ISBN = "123-356-d89";
- <>g__initLocal2.Price = 100f;
- <>g__initLocal0.Add(<>g__initLocal2);
- Book <>g__initLocal3 = new Book();
- <>g__initLocal3.Title = "Linq";
- <>g__initLocal3.ISBN = "123-d56-d89";
- <>g__initLocal3.Price = 120f;
- <>g__initLocal0.Add(<>g__initLocal3);
從上面的代碼來(lái)看,編譯器自動(dòng)的調(diào)用了List的無(wú)參構(gòu)造方法,然后實(shí)例化一個(gè)個(gè)的Book,再一個(gè)個(gè)的Add進(jìn)去,和我們?cè)瓉?lái)的做法沒(méi)有什么不同,但是,這是編譯器為我們做的,所以簡(jiǎn)省了我們很多的編碼工作。
C#對(duì)象集合初始化器就算介紹完了。有人也許會(huì)說(shuō),不就是個(gè)syntx sugar么,有什么。是的,確實(shí)是個(gè)語(yǔ)法糖。在編譯器發(fā)展早期,編譯器科學(xué)家門(mén)一直在想方設(shè)法的優(yōu)化編譯器生成的代碼,這個(gè)時(shí)候,編譯器做的主要是對(duì)機(jī)器優(yōu)化,因?yàn)槟莻€(gè)時(shí)候機(jī)器的時(shí)間非常寶貴,機(jī)器運(yùn)算速度也不快,今天我們有了足夠好的機(jī)器了(但并不是說(shuō)我們可以不關(guān)注性能的編寫(xiě)程序),而且作為編寫(xiě)軟件的人來(lái)說(shuō),比機(jī)器的時(shí)間寶貴得多,所以今天的編譯器也在向人優(yōu)化了,從編程語(yǔ)言的發(fā)展之路來(lái)講,今天的編程語(yǔ)言比昨天的語(yǔ)言更高級(jí),也更人性化了,我們只要編寫(xiě)更少的代碼,更符合人的思維的代碼,而只要關(guān)注我們值的關(guān)注的地方。體力活兒就交給編譯器吧。
【編輯推薦】