class Animal
{
        public virtual void eat()
        {
            Console.WriteLine("Animal is eating...");
        }
}

class Dog : Animal
{
        public override void eat()
        {
            Console.WriteLine("Dog is eating...");
        }

        public virtual void speak()
        {
            Console.WriteLine("hi,i am a dog.");
        }
}

class ChineseDog : Dog
{
        public new virtual void eat()
        {
            Console.WriteLine("Chinese Dog is eating...");
        }

        public override void speak()
        {
            Console.WriteLine("我是只中国狗.");
        }
}

static class Program
{
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Dog cDog = new ChineseDog();
            cDog.eat(); //此方法会调用Dog类的方法输出Dog is eating.... 
            //因为ChineseDog类中eat为虚方法.dotNet会向上调用父类
            //的方法.直到找到非虚的方法.如果没有找到非虚方法,
            //会找到最后一个new virtual方法.
            cDog.speak();//此方法会调用ChineseDog类的方法输出我是只中国狗.
            //因为ChineseDog类方法是“实“方法.
        }
}

posted on 2009-03-30 11:23  雨季  阅读(296)  评论(0编辑  收藏  举报