zoukankan      html  css  js  c++  java
  • 委托与事件

    委托是C#中最为常见的内容。与类、枚举、结构、接口一样,委托也是一种类型。类是对象的抽象,而委托则可以看成是函数的抽象。一个委托代表了具有相同参数列表和返回值的所有函数。先上一段代码:
    public class ClassA
    {
        public delegate int CalculationDelegate(int x, int y);//定义一个委托,关键字delegate
        public int Add(int x, int y)//定义一个和委托类型相同的方法
        {
            return x + y;
        }
        public int Sub(int x, int y)//定义一个和委托类型相同的方法
        {
            return x - y;
        }
        public ClassA() {
            CalculationDelegate c = Add;//实例化一个委托,并将方法赋给该委托
            int z = CalculationNum(c,1,2);//将实例化后的委托当作参数传给计算方法
        }
        public int CalculationNum(CalculationDelegate c,int x,int y)
        {
            return c(x,y);//由于传进来的方法为add,所以结果是3。类似与“模板方法模式”
        }
    }

     事件是一种特殊的委托,委托一般用于回调,而事件用于外部接口。不多说,先上代码:

    public class BaseEventCat
    {
        private string name;
        public BaseEventCat(string name)
        {
            this.name = name;
        }
        public delegate void CatShoutEventHandler();//声明委托
        public event CatShoutEventHandler CatShout;//声明事件,事件类型是委托CatShoutEventHandler
        public void Shout()
        {
            MessageBox.Show("喵喵喵,我是"+name,name);
            //如果事件被实例化了就执行猫叫事件
            if (CatShout != null)
            {
                CatShout();
            }
        }
    }
    public class BaseEventMouse
    {
        private string name;
        public BaseEventMouse(string name)
        {
            this.name = name;
        }
        public void Run()
        {
            MessageBox.Show("跑呀",name);
        }
    }
    private void Button1_Click(object sender, EventArgs e)
    {
        BaseEventCat cat = new BaseEventCat("Tom");
        BaseEventMouse mouse1 = new BaseEventMouse("Jack");
        BaseEventMouse mouse2 = new BaseEventMouse("Reber");
    
        cat.CatShout += new BaseEventCat.CatShoutEventHandler(mouse1.Run);
        cat.CatShout += new BaseEventCat.CatShoutEventHandler(mouse2.Run);
    
        cat.Shout();
    }
     
  • 相关阅读:
    Data Load Performance Optimization
    SAPBW数据仓库增量更新(转载)
    BW数据源深入研究
    SAP BW权限
    利用HTTP协议的特性进行拒绝服务攻击的一些构思
    Python自省(反射)指南 转自http://www.cnblogs.com/huxi/archive/2011/01/02/1924317.html
    交换网络中的sniffer讨论>基于交换网络的ARP spoofing sniffer
    Windows中使用精确计时器
    HTTP POST和GET的区别
    HTTP 状态代码 错误列表
  • 原文地址:https://www.cnblogs.com/liangshibo/p/12202307.html
Copyright © 2011-2022 走看看