New Feature #1: auto-implemented properties
懶的描述,請看連結XD
New Feature #2: Object and collection initializers
這一塊是我感興趣的部分。直接看程式:
1: ProcessData data = new ProcessData();
2: data.Id = 123;
3: data.Name = "MyProcess";
4: data.Memory = 123456;
上面這段程式是很常見的片段: 宣告ProcessDate的object後,初始化一些值。
用C#3.0可以寫成這樣:
var data = new ProcessData{ Id=123, Name="MyProcess", Memory=123456};
嗯, 是認真的。
如果是有constructor的class:
1: var exception = new Exception("message");
2: exception.Source = "LINQ in Action";
3: throw exception;
可以變成這樣:
throw new Exception("message") { Source = "LINQ in Action" };
相當over!!! 以上介紹的是所謂的"Object Initializer", 接下來看看"collection initializer", 他其實並不陌生:
var digits = new List<int> {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
這看起來超眼熟的,他原本應該是這樣:
1: List<int> digits = new List<int>();
2: digits.Add(0);
3: digits.Add(1);
4: digits.Add(2);
5: //....
6: digits.Add(9);
再來一個稍微麻煩一點的:
1: ProcessData tmp;
2: var processes = new List<ProcessData>();
3: //先來第一組資料
4: tmp = new ProcessData();
5: tmp.Id = 123;
6: tmp.Name = "devenv";
7: processes.Add(tmp);
8: //再來第二組資料
9: tmp = new ProcessData();
10: tmp.Id = 456;
11: tmp.Name = "firefox";
12: processes.Add(tmp);
把ojbect initializer跟collection initializer一起用:
1: var processes = new List<ProcessData> {
2: new ProcessData {Id=123, Name="devenv"},
3: new ProcessData {Id=456, Name="firefox"}
4: }
相當簡潔明瞭。以上,要這樣做,必須有一個前提XD(這麼晚才講)
This new syntax allows us to initialize different types of collections, provided they implement System.Collections.IEnumerable and provide suitable Add methods.
(take a break~) 好像還有,讀完後補。
Post a Comment