C#/.Net中的委托(Delegates)和事件(Events) 待续。。。

原文地址:Delegates and Events in C# / .NET

委托(Delegates)
C#中的委托类似于C/C++的指针功能。使用委托可以让程序员在委托对象里传引用给方法。委托对象被传递给调用引用方法的代码,而不是在编译的时候调用方法。

直接调用方法 - 不使用委托
在大多数的情况下,当我们需要调用方法的时候,我们直接调用指定的方法。如果有个类MyClass的方法Process,我们通常用这个方法调用(SimpleSample.cs):  

 1 None.gif using  System;
 2 None.gif 
 3 None.gif namespace  Akadia.NoDelegate
 4 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 5InBlock.gif    public class MyClass
 6ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 7InBlock.gif        public void Process()
 8ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 9InBlock.gif            Console.WriteLine("Process() begin");
10InBlock.gif            Console.WriteLine("Process() end");
11ExpandedSubBlockEnd.gif        }

12ExpandedSubBlockEnd.gif    }

13InBlock.gif 
14InBlock.gif    public class Test
15ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
16InBlock.gif        static void Main(string[] args)
17ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
18InBlock.gif            MyClass myClass = new MyClass();
19InBlock.gif            myClass.Process();
20ExpandedSubBlockEnd.gif        }

21ExpandedSubBlockEnd.gif    }

22ExpandedBlockEnd.gif}
 

在多数情况下是没有问题的。但是有时候,我们不想直接调用方法,更愿意能传到其他地方,以至于能够调用。当用户点击按钮等情况下,我想执行一些代码的情况发生时,类似GUI等事件驱动的系统,委托就相当有用。

非常简单的委托
委托的一个有趣而有用的属性,它不需要知道或关心它所引用的类的对象。任何的对象将能做到,问题在于方法的参数类型和返回值类型需要和委托的参数类型和返回值类型匹配。这使得委托能完美的适用于“匿名”调用。
单播委托的语句格式如下:

None.gif delegate  result - type identifier ([parameters]); 
None.gif
None.gifwhere: 
None.gifresult
- type: The result type, which matches the  return  type of the function. 
None.gifidentifier: The 
delegate  name. 
None.gifparameters: The Parameters, that the function takes. 

例如:

public delegate void SimpleDelegate ()

这个申明定义了名为SimpleDelegate的委托,能够传任何没有参数和返回值的方法。

public delegate int ButtonClickHandler (object obj1, object obj2)

这个申明定义了名为ButtonClickHandler的委托,能够传任何含有两个对象和返回值为整型的方法。

待续。。。

 

 

 

转载于:https://www.cnblogs.com/yolion/archive/2007/08/29/874442.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值