C# 委托链(多播委托)

委托既可以封装一个方法,又可以对同一类型的方法进行封装,它就是多播委托

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace DelegateTest
{
class Program
{
//申明一个委托类型,它的实例引用一个方法
//该方法传递0参数,返回void类型
public delegate string DelegateTestOne(); static void Main(string[] args)
{
//用静态方法来实例化委托
DelegateTestOne teststatic = new DelegateTestOne(Program.method1); //用实例方法来实例化委托
DelegateTestOne test2 = new DelegateTestOne(new Program().method2); //用实例方法来实例化委托
DelegateTestOne test3 = new DelegateTestOne(new Program().method3); //定义空一个委托对象
DelegateTestOne deleteAll = null;
deleteAll += teststatic;
deleteAll += test2;
deleteAll += test3;
Console.WriteLine(Test(deleteAll)); Console.ReadLine();
} public static string method1()
{ //Console.WriteLine("这是一个静态方法");
return "这是一个静态方法";
} public string method2()
{
//Console.WriteLine("这是实例方法2");
return "这是实例方法2";
} public string method3()
{
// Console.WriteLine("这是实例方法3");
return "这是实例方法3";
} //测试多播委托
public static string Test(DelegateTestOne testone)
{
if (testone == null)
{
return null;
}
StringBuilder returnstring = new StringBuilder(); Delegate[] delegatearray = testone.GetInvocationList(); foreach (DelegateTestOne t in delegatearray)
{
try
{
returnstring.Append(t() + Environment.NewLine);
}
catch (Exception e)
{ }
}
//把结果返回给调用者
return returnstring.ToString();
} }
}

运行结果:

C# 委托链(多播委托)

上一篇:django之关联field 描述子


下一篇:20155235 《Java程序设计》 实验二 实验三 敏捷开发与XP实践