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();
            }
        }
    }
    

      

  • 相关阅读:
    win查看所有wifi密码
    vsftp配置详解
    python3.7项目打包为一个exe
    ATT&CK实战系列——红队实战(一)
    PHP SECURITY CALENDAR 2017 (Day 9
    python3安装gmpy2
    [CISCN2019 总决赛 Day2 Web1]Easyweb(预期解)
    python2与python3共存及py2IDLE打不开的解决方案
    [BJDCTF 2nd]
    PHP SECURITY CALENDAR 2017 (Day 1
  • 原文地址:https://www.cnblogs.com/KTblog/p/4770144.html
Copyright © 2011-2022 走看看