1, 概述

 发送(或引发)事件的类称为“发行者”,接收(或处理)事件的类称为“订户”(MSDN)。要在类的内部声明事件,首先必须声明该事件的委托类型。委托类型定义了传递给事件处理方法的组参数。

2,示例

View Code
    public enum SwitchPosition { Up, Down }

    public class SwitchFilppedEventArgs:EventArgs
    {
        private SwitchPosition position;

        public SwitchFilppedEventArgs(SwitchPosition position) 
        {
            this.position = position;
        }

        public SwitchPosition Position { get { return position; } }
    }




    public delegate void SwitchFlippedEventHander(object sender,SwitchFilppedEventArgs e);

    public class Swatch
    {
        public event SwitchFlippedEventHander SwitchFlipped;

        public void ProcessSwitchFlippledUp()
        {
            SwitchFilppedEventArgs e = new SwitchFilppedEventArgs(SwitchPosition.Up);
            OnSwitchFlipped(e);
        }

        public void ProcessSwitchFlippledDown()
        {
            SwitchFilppedEventArgs e = new SwitchFilppedEventArgs(SwitchPosition.Down);
            OnSwitchFlipped(e);
        }

        protected virtual void OnSwitchFlipped(SwitchFilppedEventArgs e) 
        {
            if (SwitchFlipped != null) 
            {
                SwitchFlipped(this, e);
            }
        }
    }

其中Switch类编辑生成如下代码:

    // Fields
    private SwitchFlippedEventHander SwitchFlipped;

    // Events
    public event SwitchFlippedEventHander SwitchFlipped
    {
        add
        {
            SwitchFlippedEventHander hander2;
            SwitchFlippedEventHander switchFlipped = this.SwitchFlipped;
            do
            {
                hander2 = switchFlipped;
                SwitchFlippedEventHander hander3 = (SwitchFlippedEventHander) Delegate.Combine(hander2, value);
                switchFlipped = Interlocked.CompareExchange<SwitchFlippedEventHander>(ref this.SwitchFlipped, hander3, hander2);
            }
            while (switchFlipped != hander2);
        }
        remove
        {
            SwitchFlippedEventHander hander2;
            SwitchFlippedEventHander switchFlipped = this.SwitchFlipped;
            do
            {
                hander2 = switchFlipped;
                SwitchFlippedEventHander hander3 = (SwitchFlippedEventHander) Delegate.Remove(hander2, value);
                switchFlipped = Interlocked.CompareExchange<SwitchFlippedEventHander>(ref this.SwitchFlipped, hander3, hander2);
            }
            while (switchFlipped != hander2);
        }
    }

 

相关文章:

  • 2019-09-10
  • 2022-12-23
  • 2022-12-23
  • 2021-10-31
  • 2021-06-21
  • 2022-12-23
  • 2021-11-30
  • 2022-01-21
猜你喜欢
  • 2021-06-17
  • 2021-09-13
  • 2021-08-15
  • 2021-11-07
  • 2022-02-22
  • 2021-10-28
  • 2022-03-08
相关资源
相似解决方案