zoukankan      html  css  js  c++  java
  • C#

    代码:

    using System;
    
    namespace Delegate
    {
       public class Program
        {
            //声明委托
            public delegate void DelegatePait(string Name);
    
            //声明方法
            public static void A_Pait(string name)
            {
                Console.WriteLine("使用A打印的名称:{0}", name);
            }
            public static void B_Pait(string name)
            {
                Console.WriteLine("使用B打印的名称:{0}", name);
            }
    
            //声明一个可以传 递  参数为方法  的方法
            public static void Total_Pait(string name, DelegatePait pait)
            {
                pait(name);
            }
    
            //调用
            static void Main(string[] args)
            {
                //------- 普通委托的使用,使用自定义的Total委托方法 -------
    
                //此次调用传递 A_Paint为参数的Total_Pait 方法
                Total_Pait("张三", A_Pait);
    
                //此次调用传递 B_Pait为参数的 Total_Pait 方法
                Total_Pait("李四", B_Pait);
    
    
                //------- 实例化委托,不需要使用自定义的委托方法 -------
    
                //实例化委托,此时的d1,d2 代表的就是方法 A_Pait,B_Pait。
                DelegatePait d1 = new DelegatePait(A_Pait);
                DelegatePait d2 = new DelegatePait(B_Pait);
                d1("张三");
                d2("李四");
    
                //------- 将多个方法绑定到委托,并依照绑定次序依次执行 -------
    
                //可以将多个方法赋给同一个委托,或者叫将多个方法绑定到同一个委托。
                //当调用这个委托的时候,将依次调用其所绑定的方法。
                //委托对象可使用 "+=" 运算符进行合并。只有相同类型的委托可被合并。
                //"-=" 运算符可用于从合并的委托中移除组件委托。
                DelegatePait delegateshow;
                DelegatePait d1 = new DelegatePait(A_Pait);
                DelegatePait d2 = new DelegatePait(B_Pait);
                delegateshow = d1;
    
                delegateshow += d2;//添加另一个委托对象d2,执行A_Pait,B_Pait方法
                delegateshow("张三");
    
                //执行过后,从委托列表中移除委托对象d2,只执行A_Pait方法
                delegateshow -= d2;
                delegateshow("张三");
    
                Console.ReadKey();
            }
        }
    }
    

      

  • 相关阅读:
    umask设置导致的weblogic中的应用上传的文件没有权限打开
    顺序表查找及其优化(Java)
    前端能力要求
    CSS动画:旋转卡片效果
    CSS居中
    http服务器与https服务器的区别
    phpCURL抓取网页内容
    Node.js概述
    jQuery源码分析
    JavaScript学习书签
  • 原文地址:https://www.cnblogs.com/KTblog/p/4770144.html
Copyright © 2011-2022 走看看