delegate 与 event 不得不说的关系~

先来看一段代码:

/// <summary>
    /// 事件类
    /// </summary>
    public class EventClass
    {
        /// <summary>
        /// Go委托
        /// </summary>
        /// <param name="nam"></param>
        public delegate void Go(string nam);

        /// <summary>
        /// 事件委托
        /// </summary>
        public event Go GoEvent;

        /// <summary>
        /// 方法1
        /// </summary>
        /// <param name="name"></param>
        public void GoFun(string name)
        {
            Console.WriteLine(name);
        }

        /// <summary>
        /// 方法2
        /// </summary>
        /// <param name="name"></param>
        public void GoFun2(string name)
        {
            Console.WriteLine(name + "fun2");
        }

        /// <summary>
        /// 测试方法
        /// </summary>
        public void Test()
        {
            //event 无须new初始化
            Go += GoFun; //error
            GoEvent += GoFun; //success

            Go go = new Go(GoFun); //success
            GoEvent += GoFun2; //success
            go += GoFun2; //success

            //执行 - 结果一致(无区别)
            GoEvent("test");
            go("test");

        }
    }

可以看到,delegate 与 event 其实差不多,就是区别于初始化的问题。

我们再来看一组代码:

    class Program
    {

        static void Main(string[] args)
        {
            EventClass e = new EventClass();
            e.GoEvent += e.GoFun;
            e.GoEvent += e.GoFun2;

            EventClass.Go go = new EventClass.Go(e.GoFun);
            go += e.GoFun2;

            //执行
            //错误    1    事件“EventClass.GoEvent”只能出现在 += 或 -= 的左边(从类型“EventClass”中使用时除外)
            e.GoEvent("test2"); // error 
            go("test2"); //success

            Console.WriteLine("done."); 
            Console.ReadKey();
        }
    }

可以看到区别出来了:event在外部只能使用 += 或 -= 操作。

/*
     * 当有event关键字时,程序能运行正常。我把event去掉,程序也一样能运行正常。
* event只不过是限制'委托实例对象'的能力用的,是委托的子集。 * 如:事件只能进行+、- 不能直接Func(......)。而我取掉event之后,就可以直接用了。
*/

再来看看反编译会的结果:

可以看到图

Go 委托 依然有调用的方法

event 事件 只存在 add 和 remove方法

event通过对delegate的限制来封装一部分本来就不应该暴露在外的行为

posted @ 2015-08-25 10:34  颂云  阅读(289)  评论(0编辑  收藏  举报