C#继承、虚拟方法、重写、隐藏

作者(出处):百宝箱工作室发布时间:2014年9月20日 13:39:22查阅量:999

    /// <summary>
    /// Person类
    /// </summary>
    class Person
    {
        /// <summary>
        /// Person类的虚拟方法Eating()
        /// </summary>
        public virtual void Eating()
        {
            Console.WriteLine("person吃饭.");
        }    
        /// <summary>
        /// Person类的虚拟方法Sleep()
        /// </summary>
        public virtual void Sleep()
        {
            Console.WriteLine("person睡觉.");
        }
        public void Walking()
        {
            Console.WriteLine("person走路.");
        }
    }
    /// <summary>
    /// BlackMan类继承Person类
    /// </summary>
    class BlackMan : Person
    {
        /// <summary>
        /// BlackMan类重写Person类的Eating()方法
        /// </summary>
        public override void Eating()
        {
            //base.Eating();//会默认生成这句代码,我们需要对这句代码进行复写
            Console.WriteLine("BlackMan吃饭.");
        }
        /// <summary>
        /// BlackMan类重写Person类的Sleep()方法
        /// </summary>
        public override void Sleep()
        {
            //base.Sleep();//这句代码是自动生成的
            Console.WriteLine("BlackMan睡觉.");
        }
        /// <summary>
        /// 使用new关键字隐藏Person类的Walking()方法
        /// </summary>
        new public void Walking()
        {
            Console.WriteLine("BlackMan走路.");
        }
    }
    /// <summary>
    /// BlackManChild类,继承BlackMan类
    /// </summary>
    class BlackManChild : BlackMan
    {
        /// <summary>
        /// BlackManChild类重写基类的Eating()方法
        /// </summary>
        public override void Eating()
        {
            //base.Eating();
            Console.WriteLine("BlackManChild吃饭.");
        }
        /// <summary>
        /// 使用new关键字隐藏基类的Sleep()方法
        /// </summary>
        new public void Sleep()
        {
            Console.WriteLine("BlackManChild睡觉.");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            BlackMan b = new BlackMan();
            Person p1 = new BlackMan();
            Person p2 = new BlackManChild();
            //BlackMan b1 = new Person();//这样写会产生一个错误
            p.Eating();
            p.Sleep();
            p.Walking();

            b.Eating();
            b.Sleep();
            b.Walking();

            p1.Eating();
            p1.Sleep();
            p1.Walking();

            p2.Eating();
            p2.Sleep();
            p2.Walking();

            Console.Read();
        }
    }
百宝箱网络工作室  版权所有  
站长QQ:1617818397  站长E-mail:1617818397@qq.com
Powered by www.baibaox.com  Copyright © 2011-2018
点击这里给我发消息