委托与事件

委托:譬如别人 委托你买你去书挑选一本好的c#的书,而你却因为懒得动,直接去了dearbook选书,然后送上门。然后你转交给了朋友。这就是现实中的委托。-------你的好朋友并不知道,你没有去书店选。(不关注方法的细节)
c#中把委托的作用当作是给方法的签名(包括参数类型,个数,方法的返回类型)指定名称。 委托代表了方法。
为什么说委托的类型是安全的:因为在定义委托的时候就指定了它所调用的方法的签名,所以在构造委托实例的时候会判断是否正确

 2 None.gif using  System;
 3 None.gif
 4 None.gif namespace  test1
 5 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 6ExpandedSubBlockStart.gifContractedSubBlock.gif /**//// <summary>
 7InBlock.gif /// Class1 的摘要说明。
 8ExpandedSubBlockEnd.gif /// </summary>

 9InBlock.gif 
10InBlock.gif class MathsOperations
11ExpandedSubBlockStart.gifContractedSubBlock.gif dot.gif{
12InBlock.gif  public static double multiplyByTwo(double value)
13ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
14InBlock.gif   return value*2;
15ExpandedSubBlockEnd.gif  }

16InBlock.gif
17InBlock.gif  public static double Square(double value)
18ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
19InBlock.gif   return value*value;
20ExpandedSubBlockEnd.gif  }

21ExpandedSubBlockEnd.gif }

22InBlock.gif
23InBlock.gif delegate double DoubleOp(double x);
24InBlock.gif
25InBlock.gif class test1
26ExpandedSubBlockStart.gifContractedSubBlock.gif dot.gif{
27InBlock.gif  static void Main()
28ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
29InBlock.gif   DoubleOp[] operations =
30ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
31InBlock.gif     new DoubleOp(MathsOperations.multiplyByTwo),
32InBlock.gif     new DoubleOp(MathsOperations.Square)
33ExpandedSubBlockEnd.gif    }
;
34InBlock.gif
35InBlock.gif   for(int i=0;i<operations.Length;i++)
36ExpandedSubBlockStart.gifContractedSubBlock.gif   dot.gif{
37InBlock.gif    Console.WriteLine("Using operations[{0}];",i);
38InBlock.gif    ProcessAndDisplayNumber(operations[i],2.0);
39InBlock.gif    ProcessAndDisplayNumber(operations[i],5);
40InBlock.gif    Console.WriteLine();
41ExpandedSubBlockEnd.gif   }

42ExpandedSubBlockEnd.gif  }

43InBlock.gif
44InBlock.gif  static void ProcessAndDisplayNumber(DoubleOp action,double value)
45ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
46InBlock.gif   double result = action(value);
47InBlock.gif   Console.WriteLine("Value is {0},result of operation is {1}",value,result);
48ExpandedSubBlockEnd.gif  }

49ExpandedSubBlockEnd.gif }

50InBlock.gif 
51InBlock.gif
52ExpandedBlockEnd.gif}

有些时候不用委托是很难实现某些功能的
 1 None.gif      class  BubbleSorter
 2 ExpandedBlockStart.gifContractedBlock.gif     dot.gif {
 3InBlock.gif        static public void Sort(object[] sortArray,CompareOp gtMethod)
 4ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 5InBlock.gif            for(int i=0;i<sortArray.Length;i++)
 6ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 7InBlock.gif                for(int j=i+i;i<sortArray.Length;j++)
 8ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 9InBlock.gif                    if(gtMethod(sortArray[j],sortArray[i]))
10ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
11InBlock.gif                        object temp = sortArray[i];
12InBlock.gif                        sortArray[i] = sortArray[j];
13InBlock.gif                        sortArray[j] = temp;
14ExpandedSubBlockEnd.gif                    }

15ExpandedSubBlockEnd.gif                }

16ExpandedSubBlockEnd.gif            }

17ExpandedSubBlockEnd.gif        }

18ExpandedBlockEnd.gif    }

19 None.gif
20 None.gif     delegate   bool  CompareOp( object  lhs, object  rhs);
21 None.gif
22 None.gif     class  Employee
23 ExpandedBlockStart.gifContractedBlock.gif     dot.gif {
24InBlock.gif        private string name;
25InBlock.gif        private decimal salary;
26InBlock.gif
27InBlock.gif        public Employee(string name,decimal salary)
28ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
29InBlock.gif            this.name=name;
30InBlock.gif            this.salary=salary;
31ExpandedSubBlockEnd.gif        }

32InBlock.gif        public override string ToString()
33ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
34InBlock.gif            return string.Format(name + ",{0:c}",salary);
35ExpandedSubBlockEnd.gif        }

36InBlock.gif        public static bool RhslsGreater(object lhs,object rhs)
37ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
38InBlock.gif            Employee empLhs = (Employee)lhs;
39InBlock.gif            Employee empRhs = (Employee)rhs;
40InBlock.gif            return(empLhs.salary>empRhs.salary)?true:false;
41ExpandedSubBlockEnd.gif        }

42ExpandedBlockEnd.gif    }

43 None.gif
44 None.gif
45 None.gif     class  test1
46 ExpandedBlockStart.gifContractedBlock.gif     dot.gif {
47InBlock.gif        static void Main()
48ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
49InBlock.gif            Employee [] employees = 
50ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
51InBlock.gif                new Employee("abc",100),
52InBlock.gif                new Employee("bbc",122),
53InBlock.gif                new Employee("bb",111),
54ExpandedSubBlockEnd.gif            }
;
55InBlock.gif
56InBlock.gif
57InBlock.gif            CompareOp employeeCompareOp = new CompareOp(Employee.RhslsGreater);
58InBlock.gif            BubbleSorter.Sort(employees,employeeCompareOp);
59InBlock.gif
60InBlock.gif            for(int i=0;i<employees.Length;i++)
61ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
62InBlock.gif                Console.WriteLine(employees[i].ToString());
63ExpandedSubBlockEnd.gif            }

64ExpandedSubBlockEnd.gif        }

65ExpandedBlockEnd.gif    }

66 None.gif}
多播委托:委托包含多个方法。 按顺序连续调用多个方法,委托的签名必须返回void(否则,返回值应送到何处)。实际上,如果编译器发现某个委托返回void,就会自动 假定这是一个多播委托
例子:
 1 None.gif using  System;
 2 None.gif
 3 None.gif namespace  test1
 4 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 5ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
 6InBlock.gif    /// Class1 的摘要说明。
 7ExpandedSubBlockEnd.gif    ///</summary>

 8InBlock.gif    
 9InBlock.gif        class MathsOperations
10ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
11InBlock.gif            public static void multiplyByTwo(double value)
12ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
13InBlock.gif                double result = value*2;
14InBlock.gif                Console.WriteLine(
15InBlock.gif                    "Multiplying by 2:{0} gives {1}",value,result);
16ExpandedSubBlockEnd.gif            }

17InBlock.gif    
18InBlock.gif            public static void Square(double value)
19ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
20InBlock.gif                double result = value*value;
21InBlock.gif                Console.WriteLine(
22InBlock.gif                    "Squareing:{0} gives {1}",value,result);
23ExpandedSubBlockEnd.gif            }
    
24ExpandedSubBlockEnd.gif        }

25InBlock.gif    
26InBlock.gif        delegate void DoubleOp(double value);
27InBlock.gif    
28InBlock.gif        class test1
29ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
30InBlock.gif            static void Main()
31ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
32InBlock.gif                 //或,委托可以识别 +,+=,-,-=
33InBlock.gif                //DoubleOp operations = new DoubleOp(MathsOperations.multiplyByTwo);
34InBlock.gif                //operations += new DoubleOp(MathsOperations.Square);
35InBlock.gif
36InBlock.gif                DoubleOp opertaion1 = new DoubleOp(MathsOperations.multiplyByTwo);
37InBlock.gif                DoubleOp operation2 = new DoubleOp(MathsOperations.Square);
38InBlock.gif                DoubleOp operations = opertaion1 + operation2;
39InBlock.gif
40InBlock.gif                ProcessAndDisplayNumber(operations,2.0);
41InBlock.gif                ProcessAndDisplayNumber(operations,40.0);
42ExpandedSubBlockEnd.gif            }

43InBlock.gif    
44InBlock.gif            static void ProcessAndDisplayNumber(DoubleOp action,double value)
45ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
46InBlock.gif                Console.WriteLine("\nProcessAndDisplay Number called with value = " +
47InBlock.gif                    value);
48InBlock.gif                action(value);
49ExpandedSubBlockEnd.gif            }

50ExpandedSubBlockEnd.gif        }

51ExpandedBlockEnd.gif}

事件:事件与委托是密不可分的。
应用程序是通过windows来通信的,而windows又是使用预定义的消息与应用程序通信的。微软已经定义好了N多个系统事件(消息),譬如点击一个摁钮,打开一个下拉框,等等。 事件接收器就是指发生某事件时被通知的任何应用程序,对象或组件。 事件发送器可以是应用程序的一个对象或程序集。系统事件中如鼠标单击,键盘按键 。.net程序中的事件发送器就是.net的运行库,.net framework把windows消息封装在了事件中,偶没学过windows编程,对windows消息的机制不甚了解。大概就是button的click事件封装了windows的WM_MOUSECLICK消息。然后就可以直接调用click事件了。
button1.click  += new EventHandler(Button_Click);
事件              +=    实例化一个委托(某个方法)   //可多个方法依次添加到委托列表,但不能保证调用时方法的顺序。
EventHandler 委托在Farmework是已定义的,位于System命名空间,在所有的Farmework中的定义的事件都是用它。添加到该委托列表的方法都必须有相同的签名。private void Button_Click(object sender , Eventargs e) //1参:引发事件的对象,2参:包含有关事件的其他有用信息的对象,可任意类型,只要派生于它均可,譬如MouseDownEventArgs 类型。

委托和事件在用户界面程序里用的比较的多,比如象在winform或webform的用户UI上的button和它的click事件:

// 将Button1_Click()方法绑定到按钮控件Button1的Click事件上

this.Button1.Click += new System.EventHandler(this. Button1_Click);

 

private void Button1_Click(object sender, System.EventArgs e)    // Button1_Click()方法

{

                …… 

}

 

然而除了用户界面程序外,在很多其他地方也用到了事件驱动模式,比如观察者模式(Observer)或发布/订阅(Publish/Subscribe)里:在一个类里发布(Publish)某个可以被触发的事件,而其他的类就可以来订阅(Subscribe)该事件。一旦这个发布者类触发了该事件,那么运行时环境会立刻告知所有订阅了该事件的订阅者类:这个事件发生了!从而各个订阅者类可以作出它们自己的反应(调用相应方法)。

 


转载于:https://www.cnblogs.com/huoxingren/archive/2007/01/31/635270.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值