C#面向对象继承里氏转换法练习

练习

创建一个父类,四个子类,将子类赋值给父类,将父类强转为子类,随机调用子类的方法

using System;

namespace 里氏转换练习
{
    class Program
    {
        static void Main(string[] args)
        {
            Person[] per = new Person[10]; //创建一个person类数组
            Random r = new Random(); //创建一个随机数
            for (int i = 0; i < per.Length; i++) //写一个循环,让随机产生的成员进入数组
            {
                int rnumber = r.Next(1, 6); //随机数1-5
                switch (rnumber)//随机生成成员
                {
                    case 1:
                        per[i] = new Student();
                        break;
                    case 2:
                        per[i] = new Meinv();
                        break;
                    case 3:
                        per[i] = new ShuaiGe();
                        break;
                    case 4:
                        per[i] = new YeShow();
                        break;
                    case 5:
                        per[i] = new Person();
                        break;
                }
            }

            for (int i = 0; i < per.Length; i++)
            {
                //per[i].PersonSay();
                if (per[i] is Student)//如果数组里面的成员是Student子类的,将父类强转为子类成员,并输入方法
                {
                    ((Student)per[i]).StudentSay();
                }
                else if (per[i] is YeShow)//依次判断
                {
                    ((YeShow)per[i]).YeShouSay();
                }
                else if (per[i] is Meinv)
                {
                    ((Meinv)per[i]).MeiNvSay();
                }
                else if (per[i] is ShuaiGe)
                {
                    ((ShuaiGe)per[i]).ShuaiGeSay();
                }
                else
                {
                    per[i].PersonSay();
                }
            }
        }
    }

    public class Person//创建父类Person和方法
    {
        public void PersonSay()
        {
            Console.WriteLine("我是人类");
        }
    }

    public class Meinv : Person
    {
        public void MeiNvSay()
        {
            Console.WriteLine("我是美女");
        }
    }

    public class ShuaiGe : Person
    {
        public void ShuaiGeSay()
        {
            Console.WriteLine("我是帅哥");
        }
    }

    public class Student : Person
    {
        public void StudentSay()
        {
            Console.WriteLine("我是学生");
        }
    }

    public class YeShow : Person
    {
        public void YeShouSay()
        {
            Console.WriteLine("我是野兽");
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值