hello

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

posted @ 2013-01-18 22:52  B追风少年  阅读(7923)  评论(3编辑  收藏  举报

hello too