首页 > 代码库 > 里氏转换

里氏转换

概念:

1.子类可以赋值给父类

2.如果父类中装的是子类对象,那么父类可以强制转换成子类

转换关键字   is 和  as

is 转换成功返回true 失败返回false

as 转换成功返回对象,失败返回null

技术分享
using System;
namespace Dome
{
    class person {
        public void personhello() {
            Console.WriteLine("我是人类");
         }
         }
  class student:person {
      public void studenthello() {
          Console.WriteLine("我是学生");
      }
      }
  class teacher : person { 
  public void teacherhello(){
      Console.WriteLine("我是老师");
  }
  }
  class diaoyong {
      static void Main(string[] args)
      {
          student s = new student();
          s.personhello();//调用person类对象
          person p = new student(); ;//子类对象赋值给父类
          p.personhello();//父类只能调用自己的成员
          student stu = (student)p;//如果父类中装的是子类对象,那么父类可以强制转换成子类
         //转换关键字is  和  as
          if (p is student)
          {
              Console.WriteLine("转换成功");
          }
          else { Console.WriteLine("转换失败"); }

          student t = p as student;
          t.studenthello();
          
          Console.WriteLine();
          Console.ReadKey();
      }
  
  }

     }
View Code

 使用

技术分享
using System;
namespace Dome
{
    class person {
        static void Main(string[] args)
        {
            person[] pers = new person[10];
            //给数组赋值
            Random r = new Random();
            for (int i = 0; i < pers.Length;i++ ) {
                int rnum = r.Next(1,6);
                switch (rnum) { 
                    case 1: pers[i]=new student();break;
                    case 2: pers[i] = new teacher(); break;
                    case 3: pers[i] = new student(); break;
                    case 4: pers[i] = new teacher(); break;
                }
            }

            //循环输出
            for (int i = 0; i < pers.Length;i++ ) {
           if(pers[i] is student){
               ((student)pers[i]).studenthello();
           }
           else if (pers[i] is teacher) {
               ((teacher)pers[i]).teacherhello();
           }
            }
            Console.ReadKey();
        }
         }
  class student:person {
      public void studenthello() { Console.WriteLine("我是学生"); }
           }
  class teacher : person { 
        public void teacherhello(){ Console.WriteLine("我是老师");}
                       }
  

     }
View Code

 

里氏转换