集合类型初始化器(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()看上去不简洁,感觉很啰嗦。
新闻热点
疑难解答