zoukankan      html  css  js  c++  java
  • [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");
        }

    }


  • 相关阅读:
    欧拉公式
    isap的一些想法
    错误合集
    Hello World
    PAT (Advanced Level) Practice 1068 Find More Coins
    PAT (Advanced Level) 1087 All Roads Lead to Rome
    PAT (Advanced Level) 1075 PAT Judge
    PAT (Advanced Level) 1067 Sort with Swap(0, i)
    PAT (Advanced Level) 1017 Queueing at Bank
    PAT (Advanced Level) 1025 PAT Ranking
  • 原文地址:https://www.cnblogs.com/temptation/p/363588.html
Copyright © 2011-2022 走看看