c# 3.0新特性初步研究 part4:使用集合类型初始…

2008-02-23 05:42:54来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

集合类型初始化器(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()看上去不简洁,感觉很啰嗦。

http://zc1984.cnblogs.com/archive/2006/06/10/422705.html


标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇: c# 3.0新特性初步研究 part5:匿名类型_c#教程

下一篇: c# 3.0新特性初步研究 part6:使用查询表达式 _c#教程