dotNET程序员

[C#] 委托与事件(3)

2016-05-08  本文已影响0人  丑小丫大笨蛋

网上讲C#委托和事件的博文已经非常多了,其中也不乏一些深入浅出、条理清晰的文章。我之所以还是继续写,主要是借机整理学习笔记、归纳总结从而理解更透彻,当然能够以自己的理解和思路给其他人讲明白更好。
另外,太长的文章会让很多读者失去兴趣,所以我决定把这篇分成四个部分来介绍。分别是委托的基础、委托的进阶、事件的基础和事件的进阶。对使用委托与事件要求不高的同学可以跳过进阶部分。

本文开始讲事件的基础部分,前两节请参见C#委托与事件(1)C#委托与事件(2)


5. 什么是事件?怎么写一个事件?

An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object.

所以这里的事件,是指当某件有意思的事情发生时一个类给它的客户端提供通知的方法。比如说电热壶的温度被警报器订阅了,当温度达到某一高度时就会触发事件通知警报器发出报警声音。

对,关于什么是事件就是这么简单。那么,怎么写一个事件呢?
定义一个事件需要两步:
(1) 定义一个委托类型,它包含在事件触发时需要调用的方法。
(2) 通过C# event关键字用相关委托声明这个事件。
就以上面我们举得例子来写一个简单的事件吧。

namespace MyFirstEvent
{
    public delegate void BoilHandler(int p); //声明委托

    public class Heater 
    {
        private int temperature;
        public event BoilHandler BoilEvent; //声明事件

        public void BoilWater()
        {
            for (int i = 0; i <= 100; ++i)
            {
                temperature = i;
                if (temperature >= 95)
                {
                    //调用在该事件上注册的方法
                    if (BoilEvent != null) BoilEvent(temperature);
                }
            }
        }
    }

    public class Alarm
    {
        public void MakeAlert(int t)
        {
            Console.WriteLine("The temperature of water is {0} ℃", t);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Heater h = new Heater();
            Alarm a = new Alarm();

            h.BoilEvent += a.MakeAlert; //注册方法
            h.BoilWater();
        }
    }
}

输出结果:

The temperature of water is 95 ℃
The temperature of water is 96 ℃
The temperature of water is 97 ℃
The temperature of water is 98 ℃
The temperature of water is 99 ℃
The temperature of water is 100 ℃

6. 为什么要用事件?

从上面的例子看来事件和委托差不多嘛,上面的事情用委托完全可以实现,跟我们之前将的例子类似,把上面声明的事件对象换成委托对象不就可以了吗?为什么又大费周折地引入事件这么个东西呢?

那我们就来看看直接使用委托对象有什么问题吧。如果我们没有把委托成员变量定义为私有的,调用者就可以直接访问委托对象。这样,调用者不仅可以直接查看委托对象上绑定的所有方法,还可以随意地把变量重新赋值为新的委托对象。也就是说,在类中写公共的委托成员会打破类的封装,不仅会导致代码难以维护和调试,还会带来应用程序的安全风险。不要问我为什么不把委托成员声明称私有的,如果声明成私有的,那怎么在外面把客户端的方法注册到委托呢?

既然直接用委托成员存在破坏封装的问题,那为什么事件可以解决这个问题呢?
C#event关键字在编译的时候会自动提供注册和注销方法以及任何必要的委托类型成员的变量。这些委托成员变量总是声明为私有的,所有触发事件的对象不能直接访问它们。

namespace MyFirstEvent
{
    public delegate void BoilHandler(int p);

    public class Heater 
    {
        private int temperature;
        public BoilHandler BoilEvent;

        public void BoilWater()
        {
            for (int i = 0; i <= 100; ++i)
            {
                temperature = i;
                if (temperature >= 95)
                {
                    if (BoilEvent != null) BoilEvent(temperature);
                }
            }
        }
    }

    public class Alarm
    {
        public void MakeAlert(int t)
        {
            Console.WriteLine("The temperature of water is {0} ℃", t);
        }
    }

    static public class SomethingShouldNotHappen
    {
        static public void Display(int t)
        {
            Console.WriteLine("Test temperature is {0} ℃", t);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Heater h = new Heater();
            Alarm a = new Alarm();

            h.BoilEvent += a.MakeAlert;

            // get invocation list and replace it
            foreach (var d in h.BoilEvent.GetInvocationList())
            {
                Console.WriteLine(d);
            }
            h.BoilEvent = SomethingShouldNotHappen.Display;

            h.BoilWater();
        }
    }
}

输出结果:(你看,我们轻易地看到了本不该看到的invocation list,并且对委托成员上绑定的方法进行了篡改)

MyFirstEvent.BoilHandler
Test temperature is 95 ℃
Test temperature is 96 ℃
Test temperature is 97 ℃
Test temperature is 98 ℃
Test temperature is 99 ℃
Test temperature is 100 ℃

如果我们用上面的event呢?
首先,MyFirstEvent.Heater.BoilEvent不提供公开的GetInvocationList方法。实际上它什么公开的方法都不提供,你如果在VS里面输入h.BoilEvent.,你会发现VS根本就不会有任何方法提示。
其次,event扩展了两个隐藏的公共方法,一个带add_前缀,一个带remove_前缀。使用的时候可以用h.BoilEvent += x或者h.BoilEvent -= x,你想直接用=是不可能编译通过的,下面是错误信息。

Error   1   The event 'MyFirstEvent.Heater.BoilEvent' can only appear on the left hand side of += or -= (except when used from within the type 'MyFirstEvent.Heater')   c:\users\xxx\documents\visual studio 2012\Projects\MyFirstEvent\MyFirstEvent\Program.cs 54  15  MyFirstEvent

参考文献:
《精通C#》
C# 中的委托和事件
Events Tutorial

上一篇 下一篇

猜你喜欢

热点阅读