• [C#] C#的委托


    C#中的委托是通过继承System.Delegate中的一个类来实现的。

    具体的步骤:

    1. 声明一个委托对象,其参数形式一定要和你想要包含的方法的参数形式一致。
    2. 定义所有你要定义的方法,其参数形式和第一步中声明的委托对象的参数形式必须相同。
    3. 创建委托对象并将所希望的方法包含在该委托对象中。
    4. 通过委托对象调用包含在其中的各个方法。


    实现委托机制的C#代码:
    using System;

    //步骤1: 声明一个委托对象
    public delegate void MyDelegate(string input);

    //步骤2::定义各个方法,其参数形式和步骤1中声明的委托对象的必须相同
    class MyClass1{
        
    public void delegateMethod1(string input){
            Console.WriteLine(
    "This is delegateMethod1 and the input to the method is {0}",input);
        }

        
    public void delegateMethod2(string input){
            Console.WriteLine(
    "This is delegateMethod2 and the input to the method is {0}",input);
        }

    }


    //步骤3:创建一个委托对象并将上面的方法包含其中
    class MyClass2{
        
    public MyDelegate createDelegate(){
            MyClass1 c2
    =new MyClass1();
            MyDelegate d1 
    = new MyDelegate(c2.delegateMethod1);
            MyDelegate d2 
    = new MyDelegate(c2.delegateMethod2);
            MyDelegate d3 
    = d1 + d2;
            
    return d3;
        }

    }


    //步骤4:通过委托对象调用包含在其中的方法
    class MyClass3{
        
    public void callDelegate(MyDelegate d,string input){
            d(input);
        }

    }


    class Driver{
        
    static void Main(string[] args){
            MyClass2 c2 
    = new MyClass2();
            MyDelegate d 
    = c2.createDelegate();
            MyClass3 c3 
    = new MyClass3();
            c3.callDelegate(d,
    "Calling the delegate");
        }

    }


  • 相关阅读:
    java中获取服务器的IP和端口
    springboot项目 配置https
    vue+element+upload实现头像上传
    js指定日期时间加一天 ,判断指定时间是否为周末
    在内网中 vue项目添加ECharts图表插件
    vue+element树组件 实现树懒加载
    iview 表格随着更改刷新
    vue设置input不可编辑切换
    .Net程序员学用Oracle系列(3):数据库编程规范
    .Net程序员学用Oracle系列(2):准备测试环境
  • 原文地址:https://www.cnblogs.com/temptation/p/363588.html
Copyright © 2020-2023  润新知