C#事件——对委托的封装

C#中,正如属性是对成员变量的封装,事件是对委托的封装。

完整的事件流程:

    class Program
    {
        static void Main(string[] args)
        {
            EventSender sender = new EventSender();
            EventRevicer revicer = new EventRevicer();

            sender.myEvent += revicer.Action;
            
            //invoke the event
            sender.Active(new MyEventArgs("C# Event"));
        }
    }

    class MyEventArgs:EventArgs
    {
        public MyEventArgs(string name)
        {
            this.name = name;
        }
        public string name { get; set; }
    }

    delegate void MyEventHandler(EventSender sender,MyEventArgs e);

    class EventSender
    {
        private MyEventHandler myEventHandler;
        public event MyEventHandler myEvent
        {
            add
            {
                myEventHandler += value;
            }
            remove
            {
                myEventHandler -= value;
            }
        }

        public void Active(MyEventArgs e)
        {
            Console.WriteLine("I send the notification");
            myEventHandler.Invoke(this, e);
        }
    }

    class EventRevicer
    {

        internal void Action(EventSender sender, MyEventArgs e)
        {
            Console.WriteLine("I get the notification!");
        }
    }


简写的事件流程:

    class Program
    {
        static void Main(string[] args)
        {
            EventSender sender = new EventSender();
            EventRevicer revicer = new EventRevicer();

            sender.myEvent += revicer.Action;
            
            //invoke the event
            sender.Active(new MyEventArgs("C# Event"));
        }
    }

    class MyEventArgs : EventArgs
    {
        public MyEventArgs(string name)
        {
            this.name = name;
        }
        public string name { get; set; }
    }

  class EventSender
  {
      public event EventHandler myEvent;//the event
        
      public void Active(MyEventArgs e)
      {
          Console.WriteLine("I send the notification");
          myEvent.Invoke(this, e);
      }
  }

  class EventRevicer
  {

      internal void Action(object sender, EventArgs e)
      {
          //Type convert
          MyEventArgs args = e as MyEventArgs;

          Console.WriteLine("I get the notification! args:{0}",args.name);
      }
  }

注:我们平时经常用的简写流程中省略了事件封装的过程,但实际上C# 语言机制内部是有这个对委托的封装过程的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值