C# 继承中的使用new的陷阱,和abstract /virtual 的不同

假设有下面的设计:

cs 复制代码
 public class Person
 {
     public string Name { get; set; }
     public int Age { get; set; }
     public  int Height { get;}
 }

 public class Chinese: Person
 {
     public new int Height { get => 100; }
 }

基类中Height属性设计为只读,派生类中设计为可读可写,并且使用new进行覆盖;

有下方代码:

cs 复制代码
  Person me = new Chinese();
  var height = me.Height;

此时me.Height返回0;

因为声明me的时候使用的是Person类型,而Person里面Height属性的Get方法是实现的,访问的自然是Person里面Height属性,Height属性为int类型,所以初始值为0;

类似的,这个结论对于方法也适用,加入把实体像下面这样设计:

cs 复制代码
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public  int Height { get;}
    public int GetHeight()
    {
        return 0;
    }
}

public class Chinese: Person
{
    public new int Height { get => 100; }

    public new int GetHeight()
    {
        return 100;
    }
}

然后调用GetHeight方法:

cs 复制代码
 Person me = new Chinese();
 var height = me.GetHeight();

返回的height依旧是0;

想实现me.Height访问的是Chinese里面的属性,可以把实体像下面这样设计:

cs 复制代码
 public abstract class Person
 {
     public string Name { get; set; }
     public int Age { get; set; }
     public abstract int Height { get;}
 }

 public class Chinese: Person
 {
     public override int Height { get => 100; }
 }

或者:

cs 复制代码
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public virtual int Height { get;}
   
}

public class Chinese: Person
{
    public override int Height { get => 100; }
  
}

以上两种情况返回值就会是100;

由以上三种情况,针对new abstract virtual三种实现多态的关键字,在访问成员时有以下结论:

//普通方法的调用(使用new时, 调用左边类型的方法;编译时确定

//虚方法的调用,调用右边类型的方法(没有override 还是左边);运行时确定;

//抽象方法的调用,调用右边类型的方法;运行时确定;

相关推荐
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
神仙别闹3 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
kybs19913 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
孙启超3 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int3 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
CoderYanger3 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
伞伞悦读3 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json