代码改变世界

c#基础 事件

2013-05-02 23:42  Mike.Jiang  阅读(236)  评论(0)    收藏  举报

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);
        }
    }