日期:2014-05-18 浏览次数:20811 次
namespace 多态之猫咬狗 {//猫叫 完了 狗叫 猫咬了一口老鼠 老鼠叫 猫如果咬狗,狗也叫 class Program { static void Main(string[] args) { Dog d1 = new Dog(); Cat c1 = new Cat(); d1.OnBy += new BeiYaoDelegate(d1_Ontong); c1.咬(d1, 2); //d1.Is被咬(); Console.ReadKey(); } static void d1_Ontong() { Console.WriteLine("狗被咬了 汪!"); } } abstract class Animal { public int Blood { get; set; } public abstract void shout(); public abstract void 咬(Animal an,int blood); public event BeiYaoDelegate OnBy; } class Cat : Animal { public Cat() { Blood = 10; } //private BeiYaoDelegate _beiYaoDelegate; //public event BeiYaoDelegate OnBy //{ // add { _beiYaoDelegate += value; } // remove { _beiYaoDelegate -= value; } //} public new event BeiYaoDelegate OnBy; public override void shout() { Console.WriteLine("喵"); } public override void 咬(Animal an,int blood) { an.Blood -= blood; //if (Blood != 10 && _beiYaoDelegate != null) //{ // _beiYaoDelegate(); //} if (an.OnBy !=null) { an.OnBy(); } } } class Dog : Animal { public Dog() { Blood = 10; //while (true)//实时检测自己是否被咬 会死循环 不往下运行! //{ Is被咬(); } } public new event BeiYaoDelegate OnBy; public override void shout() { Console.WriteLine("旺"); } public void Is被咬() { if (Blood != 10 && OnBy != null)//如何判断被咬 { OnBy(); } } public override void 咬(Animal an, int blood) { an.Blood -= blood; } } class Mouse : Animal { public Mouse() { Blood = 10; } public override void shout() { Console.WriteLine("吱吱"); } public override void 咬(Animal an, int blood) { throw new NotImplementedException(); } } public delegate void BeiYaoDelegate();//被咬了! }