集合類型初始化器(Collection Initializers)
想看一段“奇怪”的代碼:
1class Program
2 {
3 static void Main(string[] args)
4 {
5 var a = new Point { x = 10, y = 13 };
6 var b = new Point { x = 33, y = 66 };
7
8 var r1 = new Rectangle { p1 = a, p2 = b };
9 Console.WriteLine("r1: p1 = {0},{1}, p2 = {2},{3}",
10 r1.p1.x, r1.p1.y, r1.p2.x, r1.p2.y);
11
12 var c = new Point { x = 13, y = 17 };
13 var r2 = new Rectangle { p2 = c };
14
15 Console.WriteLine("r2: p1 == {0}, p2 = {1}, {2}",
16 r2.p1, r2.p2.x, r2.p2.y);
17 }
18 }
19
20 public class Point
21 {
22 public int x, y;
23 }
24 public class Rectangle
25 {
26 public Point p1, p2;
27 }
注意到集合類型的初始化語法了嗎?直截了當!
這也是C# 3.0語法規范中的一個新特性。
也許下面的例子更能說明問題:
這是我們以前的寫法:
1class Program
2 {
3 private static List<string> keyWords = new List<string>();
4
5 public static void InitKeyWords()
6 {
7 keyWords.Add("while");
8 keyWords.Add("for");
9 keyWords.Add("break");
10 keyWords.Add("switch");
11 keyWords.Add("new");
12 keyWords.Add("if");
13 keyWords.Add("else");
14 }
15
16 public static bool IsKeyWord(string s)
17 {
18 return keyWords.Contains(s);
19 }
20 static void Main(string[] args)
21 {
22 InitKeyWords();
23 string[] toTest = { "some", "identifIErs", "for", "testing" };
24
25 foreach (string s in toTest)
26 if (IsKeyword(s)) Console.WriteLine("'{0}' is a keyWord", s);
27 }
28 }
這是我們在C# 3.0中的寫法:
1class Program
2 {
3 private static List<string> keyWords = new List<string> {
4 "while", "for", "break", "switch", "new", "if", "else"
5 };
6
7 public static bool IsKeyWord(string s)
8 {
9 return keyWords.Contains(s);
10 }
11
12 static void Main(string[] args)
13 {
14 string[] toTest = { "some", "identifIErs", "for", "testing" };
15
16 foreach (string s in toTest)
17 if (IsKeyword(s)) Console.WriteLine("'{0}' is a keyWord", s);
18 }
19 }是不是變得像枚舉類型的初始化了?
個人覺得這對提高代碼的閱讀質量是很有幫助的,
否則一堆Add()看上去不簡潔,感覺很啰嗦。