创建一个MulticastDelegateTest.cs类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpAdvancedDelegate
{
delegate void MultcastTest();
/// <summary>
/// 多播委托
/// </summary>
public class MulticastDelegateTest
{
public void Show()
{
MultcastTest multcastTest = new MultcastTest(MethodTest);
Action action = new Action(MethodTest);
//Action action = MethodTest; //也可以这样简写
action += Method2;
action += Method3;
action += Method4;
//循环遍历每一个委托
foreach (Action act in action.GetInvocationList())
{
act();
}
Func<string ,string> func = new Func<string,string >(MethodTest1);
string temp = func("我是方法MethodTest1(string str)");
Console.WriteLine(temp);
Func<string> func1 = () => { return "我是Lambda表达式,是匿名方法"; };
Console.WriteLine(func1());
func1 += () => { return "我是func2"; };
Console.WriteLine(func1());
func1 += () => { return "我是func3"; };
Console.WriteLine(func1());
}
//委托方法
private void Method4()
{
Console.WriteLine("我是Method4()方法");
}
//委托方法
private void Method3()
{
Console.WriteLine("我是Method3()方法");
}
//委托方法
private void Method2()
{
Console.WriteLine("我是Method2()方法");
}
//委托方法
public void MethodTest()
{
Console.WriteLine("我是方法MethodTest()");
}
//委托方法
public string MethodTest1(string str)
{
return str;
}
}
}
在Program.cs类中的入口类的Main函数中添加调用代码
static void Main(string[] args)
{
Console.WriteLine("=================多播委托=================");
MulticastDelegateTest multicastDelegateTest = new MulticastDelegateTest();
multicastDelegateTest.Show();
}