zoukankan      html  css  js  c++  java
  • 里氏转换

    概念:

    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
    时间就像海绵里的水,只要你愿意挤,总还是有的——鲁迅
  • 相关阅读:
    UVA
    codeforces #371div2 B
    POJ-3278 Catch That Cow
    巴士博弈
    权势二进制
    HDU
    SQL 函数
    SQL 查询语句×45
    SQL 触发器
    SQL 连接查询
  • 原文地址:https://www.cnblogs.com/syzly/p/6657521.html
Copyright © 2011-2022 走看看