程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C# 3.0新特性初步研究 Part4:使用集合類型初始化器

C# 3.0新特性初步研究 Part4:使用集合類型初始化器

編輯:關於C語言

集合類型初始化器(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()看上去不簡潔,感覺很啰嗦。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved