• 委托与事件


    委托是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();
    }
     
  • 相关阅读:
    深度学习 Deep Learning UFLDL 最新Tutorial 学习笔记 3:Vectorization
    关于gcc的一点小人性化提示
    python 命令行參数解析
    一起talk C栗子吧(第九回:C语言实例--最大公约数)
    小程序 通用请求
    小程序 上啦下拉刷新window配置
    微信小程序 功能函数 将对象的键添加到数组 (函数深入)
    微信小程序 功能函数 点击传参和页面
    微信小程序 功能函数 购物车商品删除
    微信 小程序组件 分页菜单带下划线焦点切换
  • 原文地址:https://www.cnblogs.com/liangshibo/p/12202307.html
Copyright © 2020-2023  润新知