|
C# 3.0新特性初步研究 Part4:使用集合类型初始化器
集合类型初始化器(Collection Initializers) 想看一段“奇怪”的代码:
1 class 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语法规范中的一个新特性。 也许下面的例子更能说明问题: 这是我们以前的写法:
1 class 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中的写法:
1 class 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()看上去不简洁,感觉很啰嗦。
来源:upschool.com.cn 作者: 关键字:Part4 发表日期:2006-6-12 网页显示有限 阅读全文请下载本文完整版WORD文档
上一篇:C# 3.0新特性初步研究 Part3:使用拉姆达表达式 下一篇:C# 3.0新特性初步研究 Part5:匿名类型
2008-11-21 17:13:39
|