C#预定义了一个事件委托EventHandler,定义如下:

 // Summary:
    //     Represents the method that will handle an event.
    //
    // Parameters:
    //   sender:
    //     The source of the event.
    //
    //   e:
    //     An System.EventArgs that contains the event data.
    //
    // Type parameters:
    //   TEventArgs:
    //     The type of the event data generated by the event.
    [Serializable]
    public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

可以看出委托EventHandler其实是一个泛型委托,返回值为void,有两个参数,第二个参数为泛型TEventArgs

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

如果我们的事件回调函数返回值类型为void,那么就可以用委托EventHandler来实现事件回调了,代码如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace TestApp
{
    class Program
    {
        public static void Main(string[] args)
        {
            Test tst = new Test();
            tst.InitAddEvent(AddEvent); // 传递事件处理函数地址
            tst.CallAddEvent();         // 触发事件

            Console.Read(); // 暂停程序
        }

        // 加法事件
        public static void AddEvent(object sender, EventArgs e)
        {
            AddEventData ad = (AddEventData)e;
            int c = ad.a + ad.b;
            Console.WriteLine("触发事件AddEvent, a+b={0}", c);
        }
    }

    public class Test
    {
        // 事件对象
        private event EventHandler<AddEventData> OnAddEvent;

        // 初始化事件
        public void InitAddEvent(EventHandler<AddEventData> addEvent)
        {
            //this.OnAddEvent = addEvent;   
            this.OnAddEvent += new EventHandler<AddEventData>(addEvent);
        }

        // 触发事件
        public void CallAddEvent()
        {
            if (OnAddEvent != null)
            {
                AddEventData ad = new AddEventData();
                ad.a = 1;
                ad.b = 2;
                OnAddEvent(this, ad);
            }
        }
    }

    // 事件参数,必须继承类EventArgs
    public class AddEventData:EventArgs
    {
        public int a;
        public int b;
    }
}


 

 

 

 

 

 

 

 

 

 


本文转载:CSDN博客