zoukankan      html  css  js  c++  java
  • 基类、子类之间的类型转换

    对象引用可以
    隐式向上转换为基类引用
    显式地向下转换为子类引用

    Plant是PositivePlant和NegativePlant的基类

    PositivePlant positivePlant = new PositivePlant() { Name = "阳性植物", MinimumSurvivalTemperature = 10 };
    //子转基:隐式
    Plant plant = positivePlant;
    //Plant plant = (Plant)positivePlant;//正确的写法
    //基转子:显式
    PositivePlant convertFromPlant = (PositivePlant)plant;
    //PositivePlant convertFromPlant = plant;//错误的写法
    Console.WriteLine($"positivePlant == plant:{positivePlant == plant}");//true
    Console.WriteLine($"positivePlant == convertFromPlant:{positivePlant == convertFromPlant}");//true
    
    //as运算符
    Plant plant2 = positivePlant as Plant;
    PositivePlant convertFromPlant2 = plant2 as PositivePlant;
    Console.WriteLine($"positivePlant == plant2:{positivePlant == plant2}");//true
    Console.WriteLine($"positivePlant == convertFromPlant2:{positivePlant == convertFromPlant2}");//true
    

    示例代码

    BaseAndSubClassTypeConversion

    参考资料

    C# 转换

  • 相关阅读:
    计数排序
    CSS3变形
    前端内存泄露问题
    复杂对象的深拷贝
    JavaScript基本数据类型——Symbol
    随机打乱数组
    唯一重复的数字
    src和href的区别
    iframe的缺点
    link和@import的区别
  • 原文地址:https://www.cnblogs.com/Lulus/p/12548531.html
Copyright © 2011-2022 走看看