C#委托与事件

来源:互联网 发布:几米漫画推荐知乎 编辑:程序博客网 时间:2024/06/07 21:00

简单来说委托与事件就是定义某一事件发生时执行此时委托要执行的处理函数,Delegate类型提供函数指针的功能,类似于回调函数。

1.定义委托

public delegate void DelegateClassHandle(object sender, EvetnArgs e); 

定义一个委托的过程类似方法的定义,但它没有方法体。定义委托一定要添加关键字delegate。由于定义委托实际上相当一个类,因此可以在定义类的任何地方定义委托。另外,根据委托的可见性,也可以添加一般的访问修饰符,如public、private和protected。委托的返回值类型为void,这并非表示委托类型本身带有返回值,该返回值类型是指委托的目标函数类型,即它委托的一个事件处理函数返回值是void类型。委托的返回值类型也可以为int,string...等其它类型。

一般情况下,事件的响应方法中都有两个参数,其中第一个代表引发事件的对象即sender,由于引发事件的对象不可预知的,因此我们把其声明成为object类型,所有的对象都适用。第二个参数代表引发事件的具体信息,各种类型的事件中可能不同,这要根据类中事件成员的说明决定。事件的参数可以设置为任何类型的数据,在.NET框架中,还提供了事件参数基类EventArgs专门用于传递事件数据。 从该EventArgs类派生一个自定义的事件参数类MyEventArgs来封装你要传递的参数。类似于c/c++里的无类型指针LPVOID。

这样,所有形如:void 函娄名(object 参数名,MyEventArgs 参数名);的函数都可以作为DelegateClassHandle()委托的响应方法了。


2.定义事件

public event DelegateClassHandle SomethingHappened;
它的定义方式也很特殊,首先必须使用关键字event,表示SomethingHappened是一个事件,同时还必须声明该事件的委托类型为DelegateClassHandle,即将来由该类型的委托对象负责通知事件。


3.定义处理函数

返回值类型 func (object 参数名,MyEventArgs 参数名)
{
//写你的代码
}
 事件处理程序必须具有与为事件声明的委托相同的方法签名,即相同的参数和返回值类型。


4.绑定事件与委托


SomethingHappened+= new DelegateClassHandle( func); 


示例:
当计数器值等于或者超过阈值时,将引发此事件,并调用函数。

<span style="font-size:14px;">using System;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            Counter c = new Counter(new Random().Next(10));            c.ThresholdReached += c_ThresholdReached;            Console.WriteLine("press 'a' key to increase total");            while (Console.ReadKey(true).KeyChar == 'a')            {                Console.WriteLine("adding one");                c.Add(1);            }        }        static void c_ThresholdReached(Object sender, ThresholdReachedEventArgs e)        {            Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);            Environment.Exit(0);        }    }    class Counter    {        private int threshold;        private int total;        public Counter(int passedThreshold)        {            threshold = passedThreshold;        }        public void Add(int x)        {            total += x;            if (total >= threshold)            {                ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();                args.Threshold = threshold;                args.TimeReached = DateTime.Now;                OnThresholdReached(args);            }        }        protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)        {            ThresholdReachedEventHandler handler = ThresholdReached;            if (handler != null)            {                handler(this, e);            }        }        public event ThresholdReachedEventHandler ThresholdReached;    }    public class ThresholdReachedEventArgs : EventArgs    {        public int Threshold { get; set; }        public DateTime TimeReached { get; set; }    }    public delegate void ThresholdReachedEventHandler(Object sender, ThresholdReachedEventArgs e);}</span>


0 0
原创粉丝点击