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

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

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

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

 1using System;
 2 
 3namespace Akadia.NoDelegate
 4{
 5    public class MyClass
 6    {
 7        public void Process()
 8        {
 9            Console.WriteLine("Process() begin");
10            Console.WriteLine("Process() end");
11        }

12    }

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

21    }

22}
 

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

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

delegate result-type identifier ([parameters]); 

where: 
result
-type: The result type, which matches the return type of the function. 
identifier: The 
delegate name. 
parameters: The Parameters, that the function takes. 

例如:

public delegate void SimpleDelegate ()

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

public delegate int ButtonClickHandler (object obj1, object obj2)

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

待续。。。

 

 

 

posted on 2007-08-29 13:24  Yolion  阅读(311)  评论(0编辑  收藏  举报