• C#多播委托


    每个委托都只包含一个方法调用,调用委托的次数与调用方法的次数相同。如果调用多个方法,就需要多次显示调用这个委托。当然委托也可以包含多个方法,这种委托称为多播委托。

    当调用多播委托时,它连续调用每个方法。在调用过程中,委托必须为同类型,返回类型一般为void,这样才能将委托的单个实例合并为一个多播委托。如果委托具有返回值和/或输出参数,它将返回最后调用的方法的返回值和参数。(有些书上和博客说多播委托返回类型必须为void,并且不能带输出参数,只能带引用参数,是错误的)。

    如下:

    /// <summary>
    
    /// 多播委托
    
    /// </summary>
    
    public class MultiDelegate
    
    {
    
    private delegate int DemoMultiDelegate(out int x);
    
    private static int Show1(out int x)
    
    {
    
    x = 1;
    
    Console.WriteLine("This is the first show method:"+x);
    
    return x;
    
    }
    
    private static int Show2(out int x)
    
    {
    
    x = 2;
    
    Console.WriteLine("This is the second show method:"+x);
    
    return x;
    
    }
    
    private static int Show3(out int x)
    
    {
    
    x = 3;
    
    Console.WriteLine("This is the third show method:"+x);
    
    return x;
    
    }
    
    /// <summary>
    
    /// 调用多播委托
    
    /// </summary>
    
    public void Show()
    
    {
    
    DemoMultiDelegate dmd = new DemoMultiDelegate(Show1);
    
    dmd += new DemoMultiDelegate(Show2);
    
    dmd += new DemoMultiDelegate(Show3);//检查结果
    
    int x = 5;
    
    int y= dmd(out x);
    
    Console.WriteLine(y);
    
    }
    
    }

    调用:

    /*----------------------多播委托---------------------------------*/
    
    MultiDelegate multiDelegate = new MultiDelegate();
    
    multiDelegate.Show();

    输出:

    clip_image002

  • 相关阅读:
    guzzle 中间件原理
    K8S-K8S 环境搭建
    K8S-k8s 理念知识
    云计算的概念
    Linux-DHCP 交互的过程
    linux-怎么踢出系统当前已连接的用户
    linux-Centos 搭建http yum源
    linux-硬链接与软连接
    linux-centos网络配置bond
    linux-dd 一个测试文件
  • 原文地址:https://www.cnblogs.com/bianlan/p/2867065.html
Copyright © 2020-2023  润新知