对象初始化器和集合初始化器,类似自动属性,一种省事的写法,参见下例绿色部分:
1 namespace Demo 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 //以前我们可能这么写 8 //对象 9 Person p1 = new Person();10 p1.Name = "Joey";11 p1.Age = 25;12 //集合13 Listps1 = new List ();14 Person joey = new Person();15 joey.Name = "joey";16 joey.Age = 25;17 Person zhangSan = new Person();18 zhangSan.Name = "ZhangSan";19 zhangSan.Age = 18;20 //然后加入集合21 ps1.Add(joey);22 ps1.Add(zhangSan);23 //数组24 int[] a1 = new int[3];25 a1[0] = 1;26 a1[1] = 2;27 a1[2] = 3;28 29 //有了初始化器后 我们可以这么写30 //对象31 var p2 = new Person { Name = "Joey", Age = 25 };32 33 //集合34 var ps2 = new List { 35 new Person{ Name="Joey", Age=25 },36 new Person{Name="ZhangSan", Age=18 }37 };38 //数组39 var a2 = new int[] { 1, 2, 3 };40 }41 }42 43 public class Person44 {45 public int ID { get; private set; }46 47 public string Name { get; set; }48 public int Age { get; set; }49 50 }51 }