zoukankan      html  css  js  c++  java
  • C# 委托与事件区别简单总结

      前天接了个电话面试,被问到事件与委托的区别,虽然一直用但真要你说有什么区别一时半会还真说不上来。于是问google老师,得到如下答案:

       1.事件的声明只是在委托前面加一个event关键词,虽然你可以定义一个public,但是有了event关键词后编译器始终会把这个委托声明为private,然后添加1组add,remove方法。add对应+=,remove对应-=。这样就导致事件只能用+=,-=来绑定方法或者取消绑定方法。而委托可以用=来赋值,当然委托也是可以用+=,-=来绑定方法的(面试我的那个哥们好像说不行)。

      2.委托可以在外部被其他对象调用,而且可以有返回值(返回最后一个注册方法的返回值)。而事件不可以在外部调用,只能在声明事件的类内部被调用。我们可以使用这个特性来实现观察者模式。大概就是这么多。下面是一段测试代码。

    namespace delegateEvent
    {
        public delegate string deleFun(string word);
    
        public class test
        {
            public event deleFun eventSay;
            public deleFun deleSay;
            public void doEventSay(string str)
            {
                if (eventSay!=null)
                    eventSay(str);
            }
        }
    
    
        class Program
        {
            static void Main(string[] args)
            {
                test t = new test();
                t.eventSay += t_say;
                t.deleSay += t_say;
                t.deleSay += t_say2;
                //t.eventSay("eventSay"); 错误 事件不能在外部直接调用
                t.doEventSay("eventSay");//正确 事件只能在声明的内部调用
                string str = t.deleSay("deleSay");//正确 委托可以在外部被调用 当然在内部调用也毫无压力 而且还能有返回值(返回最后一个注册的方法的返回值)
                Console.WriteLine(str);
                Console.Read();
            }
    
            static string t_say(string word)
            {
                Console.WriteLine(word);
    
                return "return "+word;
            }
    
            static string t_say2(string word)
            {
                Console.WriteLine(word);
    
                return "return " + word + " 2";
            }
        }
    }
  • 相关阅读:
    面向对象定义
    xml与面上对象初识
    模块configparser/subprocess/表格处理模块
    python模块
    python-判断语句
    python了解
    Qt Qwdget 汽车仪表知识点拆解7 图像绘制,旋转
    Qt Qwdget 汽车仪表知识点拆解6 自定义控件
    Qt Qwdget 汽车仪表知识点拆解5 标题栏图标闪烁
    Qt Qwdget 汽车仪表知识点拆解4 另类进度条实现
  • 原文地址:https://www.cnblogs.com/kklldog/p/2324228.html
Copyright © 2011-2022 走看看