namespace DelegatesCS { using System;
public class Wisdom //包含代理的类 { public delegate string GiveAdvice(); public string OfferAdvice(GiveAdvice Words) { return Words(); } } public class Parent //基类 { public virtual string Advice() { return("Listen to reason"); } ~Parent() {} } public class Dad: Parent //子类 { public Dad() {} public override string Advice() { return("Listen to your Mom"); } ~Dad() {} } public class Mom: Parent //子类 { public Mom() {} public override string Advice() { return("Listen to your Dad"); } ~Mom() {} } public class Daughter //不继承与基类的类 { public Daughter() {} public string Advice() { return("I know all there is to life"); } ~Daughter() {} }
public class Test { public static string CallAdvice(Parent p)//使用基类 { Wisdom parents = new Wisdom(); Wisdom.GiveAdvice TeenageGirls = new Wisdom.GiveAdvice(p.Advice);//将Advice方法委托给TeenageGirls委托对象 return(parents.OfferAdvice(TeenageGirls)); }
public static void Main() { Dad d = new Dad(); Mom m = new Mom(); Daughter g = new Daughter(); //以下两个为衍于基类的类 Console.WriteLine(CallAdvice(d)); Console.WriteLine(CallAdvice(m)); //以下为未衍于基类的类,如果调用将出错。 //Console.WriteLine(CallAdvice(g)); } } }