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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM