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

转载于:https://www.cnblogs.com/bianlan/archive/2013/01/18/2867065.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值