zoukankan      html  css  js  c++  java
  • 继承(is与as)

    is操作符用于检查对象和指定的类型是否兼容

    as操作符主要用于二个对象之间的类型转换

     //父类
      public   class Animal
        {
          public int age;
        }

     //子类
       public class Cat:Animal
        {
           public string name;
           //无参构造
           public Cat()
           {

           }
           //有参构造
           public Cat(int age, string name)
           {
               this.age = age;
               this.name = name;
           }

    }

     //子类
       public class Dog:Animal
        {
           public string color;
           //无参构造
           public Dog()
           {

            }
           //有参构造
           public Dog(int age, string color)
           {
               this.age = age;
               this.color = color;
           }
        }

       //测试类
          public  static void Main(string[] args)
            {
                List<Animal> list = new List<Animal>()  //范型集合
                {
                    new Cat(15,"毛毛"),
                    new Dog(10,"灰色")
                };

                foreach (Animal animal in list)
                {
                    if(animal is Cat)
                    {
                        Cat cat = (Cat)animal;   //类型强制转换
                        Console.WriteLine(cat.age + " "+cat.name);
                     }

                    if (animal is Dog)   //is主要做类型判定
                    {
                        //Dog dog = (Dog)animal;  //类型强制转换
                        Dog dog = animal as Dog; //as做类型转换
                        Console.WriteLine(dog.age + " "+dog.color);
                    }
                }
                Console.ReadKey();
            }

  • 相关阅读:
    BZOJ 3295 【CQOI2011】 动态逆序对
    POJ 3714 Raid
    树状数组区间修改加区间查询
    codevs 2606 约数和问题
    UOJ #150 【NOIP2015】 运输计划
    分享知识-快乐自己:IDEA 导入(web)项目并部署到 Tomcat
    分享知识-快乐自己:配置(各种)环境变量
    分享知识-快乐自己:什么是MVC
    分享知识-快乐自己:SpringBoot 使用注解API的方式定义启动端口号
    分享知识-快乐自己:Oracle中定义及使用同义词
  • 原文地址:https://www.cnblogs.com/sujulin/p/7066159.html
Copyright © 2011-2022 走看看