在上一篇《C#4.0的dynamic和var及object關鍵字辨析》中溫習了.net 4.0的dynamic關鍵字,今天看看C#的delegate/event/Action/Func/Predicate關鍵字,它們基本上.net 2.0-3.0就有了,不是新的,但新手容易暈。
回顧C#發展的曆史,C#1.0完全是模仿Java,並保留了C/C++的一些特性如struct,新學者很容易上手;C#2.0加入了泛型,也與 Java1.5的泛型如出一轍;C#3.0加入了一堆文法糖,並在沒有修改CLR的情況下引入了Linq,簡直是神來之筆,雖然很多項目出於各種各樣如效能之類的原因沒有採用,但非常適合小型程式的快速開發,減輕了程式員的工作量,也提高了代碼的可讀性;C#4.0增加了動態語言的特性,從裡面可以看到很多javascript、python這些動態語言的影子。雖然越來越偏離靜態語言的道路,但從另一個角度來說,這些特性也都是為了提高程式員的生產力。至於被接受與否,還是讓時間來說話吧。
好了,看看C#的delegate/event/Action/Func/Predicate關鍵字,直接上代碼:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace ConsoleApplication1
7: {
8: class Program
9: {
10: public class Test
11: {
12: public delegate void WriteName(string name); //定義委託
13: public static event WriteName WriteNameEvent; //定義事件
14: }
15:
16: static Action<string> WriteNameAction;//Action是參數從0到4,傳回型別為void(即沒有傳回值)的委託
17: static Func<string, int> WriteNameFunction;//Func的參數從1到5個,有傳回值的委託,最後一個是傳回型別
18:
19: static void Main(string[] args)
20: {
21: Test.WriteName myDelegate = x => { Console.WriteLine("abc,{0}!", x); }; // 使用 Lambda 運算式
22: myDelegate("teststring");
23:
24: Test.WriteName w = (string name) => { Console.WriteLine("Hello,{0}!", name); };//使用匿名委託
25: w("Jimmy");
26:
27: Test.WriteNameEvent += (string name) => { Console.WriteLine("Hello,{0}!", name); };//使用匿名委託
28: Test.WriteNameEvent += delegate(string name) { Console.Write("test"); }; //使用匿名方法(.net 2.0)
29:
30: WriteNameAction = HelloWrite; // 匿名委託,和這個一樣:WriteNameAction = new Action<string>(HelloWrite);
31: WriteNameAction("test");
32:
33: WriteNameAction = (string name) => { Console.WriteLine("hello,{0}!", name); };//使用匿名委託
34: WriteNameAction("test2");
35:
36:
37: WriteNameFunction = HelloWrite2; // 匿名委託,和這個一樣:WriteNameFunction = new Func<string, int>(HelloWrite2);
38: Console.WriteLine(WriteNameFunction("test3"));
39:
40: Predicate<int[]> preTest = i => i.Length == 10;
41:
42: Console.Read();
43:
44: }
45:
46: static List<String> listString = new List<String>()
47: {
48: "One","Two","Three","Four","Fice","Six","Seven","Eight","Nine","Ten"
49: };
50:
51: static List<String> GetFirstStringFromList()
52: {
53: string str = GetStringList(a => { return a.Length <= 3 && a.Contains('S'); });// 使用 Predicate 泛型委派
54:
55: return listString.FindAll((c) => { return c.Length <= 3; });// 使用 Predicate 泛型委派
56: }
57:
58: static String GetStringList(Predicate<String> p) // 使用 Predicate 泛型委派
59: {
60: foreach (string item in listString)
61: {
62: if (p(item))
63: return item;
64: }
65: return null;
66: }
67:
68: static void HelloWrite(string name)
69: {
70: Console.WriteLine("Hello world,{0}!", name);
71: }
72:
73: static int HelloWrite2(string name)
74: {
75: Console.WriteLine("Hello world,{0}!", name);
76: return 1;
77: }
78: }
79: }