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 还是左边);运行时确定;

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

相关推荐
yuhulkjv33519 小时前
Claude表格复制到word不再崩溃,AI导出鸭批量导出+格式无损一键搞定
人工智能·ai·c#·word·ai导出鸭
WWJA王文举21 小时前
I²C通信完整流程详解:START、地址、ACK、数据、Repeated START和STOP一次讲透
c语言·开发语言
zhanghaha131421 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
qq_448011161 天前
C语言中的动态内存分配
c语言·开发语言·php
汉字萌萌哒1 天前
2024CSP-J入门级C++真题详解
开发语言·c++
arbboter1 天前
【网络工具】NetProxy网络代理用户手册
开发语言·网络·c#·网络代理·网络异常·代理工具
微小冷1 天前
海康威视相机C#二次开发环境配置
数码相机·c#·.net·海康威视·相机开发
汉字萌萌哒1 天前
2019CCF-CSP入门级C++试题解析
java·开发语言·c++
叠层归一研究院1 天前
AGI 系统(十一):二阶网络 — 二阶递归 × 多主体 (元符号网络)
开发语言·人工智能·算法·php·agi
小雨笙笙1 天前
C语言:变量三属性——存储类型
c语言·开发语言