zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    HTML+JSP的登录界面数据库链接
    链式前向星模板
    【洛谷【模板】最小生成树】
    【洛谷P1090 合并果子】
    Dijkstra【迪杰斯特拉算法】
    Bellman-Ford&&SPFA
    【一本通1248:Dungeon Master&&洛谷UVA532 Dungeon Master】
    【一本通1329:【例8.2】细胞&&洛谷P1451 求细胞数量】
    Floyed-Warshall【弗洛伊德算法】
    广搜
  • 原文地址:https://www.cnblogs.com/bianlan/p/2867065.html
Copyright © 2011-2022 走看看