Delegate的使用
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5:
6: namespace ConsoleApplication4
7: {
8: class Program
9: {
10: static void Main(string[] args)
11: {
12: Operations["+"] = (int lhs, int rhs) => lhs + rhs;
13: Operations["-"] = (int lhs, int rhs) => lhs - rhs;
14: Operations["*"] = (int lhs, int rhs) => lhs * rhs;
15: Operations["/"] = (int lhs, int rhs) => lhs / rhs;
16:
17: int A = 10;
18: int B = 2;
19: Console.WriteLine("+={0}", Operate(A, "+", B));
20: Console.WriteLine("-={0}", Operate(A, "-", B));
21: Console.WriteLine("*={0}", Operate(A, "*", B));
22: Console.WriteLine("/={0}", Operate(A, "/", B));
23: }
24:
25: interface ICalcOp {
26: int Execute(int lhs,int rhs);
27: }
28:
29: class AddOp : ICalcOp {
30:
31: #region ICalcOp 成員
32:
33: public int Execute(int lhs, int rhs)
34: {
35: return lhs + rhs;
36: }
37:
38: #endregion
39: }
40:
41: delegate int CalcOp(int lhs, int rhs);
42: private static Dictionary<string, CalcOp> Operations = new Dictionary<string, CalcOp>();
43:
44: static int Operate(int lhs, string op, int rhs) {
45: CalcOp oper = Operations[op];
46: return oper(lhs, rhs);
47: }
48:
49:
50: }
51: }
52:
53:
54:
55: