調用對應Class的對應的Constructor創建一個臨時對象。
Collection Initializer
使用集合初始化器,如下:
1 List<staff> myListOfstaff = new List<staff>
2 {
3 new staff {Name = "GUOJUN", Age = 27 },
4 new staff {Name = "IORI", Age = 27 },
5 new staff(12, "sss") { Name = "GUOJUN" }
6 };
7 foreach (staff pt in myListOfstaff)
8 {
9 Console.WriteLine (pt);
10 }
分析Object Initializer的本質一樣,我們之後看看通過Compiler變 異後的Code是什麼樣子,就會對Collection Initializer的實現有一個全面的了 解:
1 List<staff> <>g__initLocal6 = new List<staff>();
2 staff <>g__initLocal7 = new staff ();
3 <>g__initLocal7.Name = "GUOJUN";
4 <>g__initLocal7.Age = 0x1b;
5 <>g__initLocal6.Add (<>g__initLocal7);
6 staff <>g__initLocal8 = new staff();
7 <>g__initLocal8.Name = "IORI";
8 <>g__initLocal8.Age = 0x1b;
9 <>g__initLocal6.Add (<>g__initLocal8);
10 staff <>g__initLocal9 = new staff(12, "sss");
11 <>g__initLocal9.Name = "GUOJUN";
12 <>g__initLocal6.Add (<>g__initLocal9);
13 List<staff> myListOfstaff = <>g__initLocal6;
14 foreach (staff pt in myListOfstaff)
15 {
16 Console.WriteLine(pt);
17 }
18 Collection Initializer的實現和Object Initializer很類似。