1、简单委托的构成
//定义一个委托类型
//返回类型为void
//入参为string类型
delegate void StringProcessor(string input);
class Person
{
string name;
public Person(string name) { this.name = name; }
//创建和委托类型兼容的方法,返回类型为void,入参类型为string
public void Say(string message)
{
Console.WriteLine("{0} says {1}", name, message);
}
}
class Background
{
//创建和委托类型兼容的方法,返回类型为void,入参类型为string
public static void Note(string note)
{
Console.WriteLine("({0})", note);
}
}
//Main方法中调用
Person jon = new Person("Jon");
Person tom = new Person("Tom");
//创建委托的三个实例
StringProcessor jsonVoice, tomVoice, background;
//将Say方法 赋给给委托
jsonVoice = new StringProcessor(jon.Say);
tomVoice = new StringProcessor(tom.Say);
//将Note方法 赋给给委托
background = new StringProcessor(Background.Note);
//调用委托实例
jsonVoice("hello , son");
//使用Invoke显示调用委托实例
tomVoice.Invoke("hello,Daddy");
background(" an airPlane flies past");
2、合并和删除委托
委托实例可能会有不止一个操作。委托实例实际有一个操作列表与之关联。这称为委托实例的调用列表。
System.Delegate类型的静态方法Combine和Remove负责创建新的委托。Combine是将两个委托连接在一起,Remove负责从一个委托实例中删除另一个实例的调用列表
但是在C#代码中很少有使用Combine和Remove方法的,一般都是使用+、+=、-、-=符号。
delegate void CustomDel(string s);
static void Hello(string s)
{
System.Console.WriteLine(" Hello :{0}", s);
}
static void Goodbye(string s)
{
System.Console.WriteLine(" Goodbye,{0}", 2);
}
//Main方法调用
CustomDel hiDel, byeDel, multiDel, multiMinusHiDel;
hiDel = Hello;
byeDel = Goodbye;
//multiDel = (CustomDel)Delegate.Combine(hiDel, byeDel);
//multiMinusHiDel = (CustomDel)Delegate.Remove(multiDel, hiDel);
multiDel = hiDel+byeDel;
multiMinusHiDel = multiDel-hiDel;
Console.WriteLine("Invoking delegate hiDel:");
hiDel("A");
Console.WriteLine("Invoking delegate byeDel:");
byeDel("B");
Console.WriteLine("Invoking delegate multiDel:");
multiDel("C");
Console.WriteLine("Invoking delegate multiMinusHiDel:");
multiMinusHiDel("D");