该例子摘自:《C#程序设计教程》--朱毅华等 第132页
using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate
{
public class WorkerClass
{
public int InstanceMethod(int nID, string sName)
{
int retval = 0;
retval = nID * sName.Length;
Console.WriteLine("调用InstanceMethod方法");
return retval;
}
public static int StaticMethod(int nID, string sName)
{
int retval = 0;
retval = nID * sName.Length + 2;
Console.WriteLine("调用StaticMethod方法");
return retval;
}
public delegate int SomeDelegate(int nID, string sName); //--参数等必须和要指向的方法一样
static void Main(string[] args)
{
WorkerClass wr = new WorkerClass();
SomeDelegate d1 = new SomeDelegate(wr.InstanceMethod); //--只是挂钩,尚未执行InstanceMethod方法
Console.WriteLine("Invoking delegate InstanceMethod, return={0}", d1(5, "aaa")); //--先调用执行InstanceMethod方法,再执行该Console方法;
SomeDelegate d2 = new SomeDelegate(WorkerClass.StaticMethod);
Console.WriteLine("Invoking delegate StaticMethod, return={0}", d2(5, "aaa"));
Console.WriteLine("...........");
Console.WriteLine("测试多播......");
SomeDelegate d3 = d2 + d1; //--按组装的次序来进行调用;先执行d2,再执行d1
Console.WriteLine("d1 And d2 return={0}", d3(5, "aaa"));//--按组装的次序来进行调用;先执行d2,再执行d1
Console.WriteLine("..................................");
int num_method = d3.GetInvocationList().Length;
Console.WriteLine("Number of Methods d3:{0}", num_method);
d3 = d3 - d2;
Console.WriteLine("d3 - d2 return={0}", d3(5, "aaa"));
Console.WriteLine("..................................");
num_method = d3.GetInvocationList().Length; //--该委托里还有几个方法;
Console.WriteLine("Number of Methods d3:{0}", num_method);
Console.ReadKey();
}
}
}