Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)delv
published in(发表于) 2014/1/6 9:05:39
C#,3.0新特性初步研究,Part4:使用集合类型初始化器_[Asp.Net教程]

C# 3.0新特性初步研究 Part4:使用集合类型初始化器_[Asp.Net教程]

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


来源:网络







If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759