当前位置:编程学习 > C#/ASP.NET >>

C#事件简单举例

EventHandler<TEventArgs>的定义如下
public delegate void EventHandler<TEventArgs>(object sender,TEventArgs e) where TEventArgs:EventArgs
第一个参数必须是object类型(是一个对象,包含事件的发送者)
第二个参数是T类型(即泛型),定义了一个T的约束,它必须派生自基类EventArgs
CardInfoEventArgs 就派生自基类EventArgs

 

-----------举例---------------
    #region 测试事件1

    //EventArgs类
    public class CardInfoEventArgs : EventArgs
    {
        public string Car { get; private set; }
        public CardInfoEventArgs(string car)
        {
            this.Car = car;
        }
    }

    //触发事件的类
    public class CarDealer
    {
        public event EventHandler<CardInfoEventArgs> NewCardInfo;

        public void NewCar(string car)
        {
            Console.WriteLine("CarDealer,new car{0}", car);
            //在触发事件之前,需要检查委托NewCardInfo是否不为空。如果没有订阅处理程序,委托就是空
            if (NewCardInfo != null)
            {
                NewCardInfo(this, new CardInfoEventArgs(car));
            }
        }
    }

    //处理事件的类
    public class Consumer
    {
        private string name;

        public Consumer(string name)
        {
            this.name = name;
        }
        //处理事件的方法
        public void NewCarIsHere(object sender, CardInfoEventArgs e)
        {
            Console.WriteLine("{0}:car {1} is new", name, e.Car);
        }
    }
    #endregion

        private void button_测试事件1_Click(object sender, EventArgs e)
        {
            CarDealer dealer = new CarDealer();
            Consumer michael = new Consumer("Michael");
            dealer.NewCardInfo += michael.NewCarIsHere;      //订阅事件
            dealer.NewCar("宝马");
            Consumer nick = new Consumer("Nick");
            dealer.NewCardInfo += nick.NewCarIsHere;         //订阅事件
            dealer.NewCar("奔驰");

            dealer.NewCardInfo -= michael.NewCarIsHere;      //取消订阅事件
            dealer.NewCar("奥迪");
        }

 

       -----测试结果截图-------

      

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,