11002 里氏替换原则实例:Person对应各个国家的调用 源代码 – 恵玩科技

program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace day11
{
    class Program
    {
        static void Main(string[] args)
        {
            //里氏替换原则练习
            Person[] pers = { new Person(), new Chinese(), new Korea(), new American (),new English() };
            for (int i=0;i<pers.Length;i++)
            {
                //需要转换
                if(pers[i] is Chinese)
                {
                    ((Chinese)pers[i]).sayHello();
                }else if (pers[i] is American)
                {
                    ((American)pers[i]).sayHello();
                }else if (pers[i] is English)
                {
                    ((English)pers[i]).sayHello();
                }else if(pers[i] is Korea)
                {
                    ((Korea)pers[i]).sayHello();
                }
                else
                {
                    //会先调用父类---->所以,父类的sayHello方法最先显示
                    pers[i].sayHello();
                }
                
            }

            Console.ReadKey();
        }
    }
}

LiiCiChang.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace day11
{
    class LiChange
    {

    }
    class Person
    {
        public void sayHello()
        {
            Console.WriteLine("我是人类!");
        }
        
    }
    class Chinese : Person
    {
        public void sayHello()
        {
            Console.WriteLine("我是中国人!");
        }
    }

    class Korea : Person
    {
        public void sayHello()
        {
            Console.WriteLine( "我是韩国人!");
        }
    }

    class English : Person
    {
        public void sayHello()
        {
            Console.WriteLine("我是英国人!");
        }
    }
    class American : Person
    {
        public void sayHello()
        {
            Console.WriteLine("我是美国人!");
        }
    }

}

 

打赏作者