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

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

相关推荐
拉勾科研工作室11 分钟前
区块链工程毕业论文题目【249个】
开发语言·javascript
雪豹阿伟1 小时前
21.Winfrom —— 定时器、日期选择器、进度条、表格、DataTable
c#·上位机·winfrom
z落落1 小时前
C#WinForm控件实战:Panel与单选框动态创建
开发语言·c#
ptc学习者1 小时前
python 中描述符@property property 大概的样子
开发语言·python
zmzb01031 小时前
Python课后习题训练记录Day129
开发语言·python
张忠琳1 小时前
【Go 1.26.4】Golang Map 深度解析
开发语言·后端·golang
Vertira1 小时前
如何对QT开发的软件进行打包[已解决]
开发语言·qt
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题 第110题】【并发篇】第10题:CAS 存在哪些问题?
java·开发语言·面试
石一峰6991 小时前
C 语言函数设计模式实战经验
c语言·开发语言·设计模式
sitellla1 小时前
Pydub:用 Python 处理音频,不写废话
开发语言·python·其他·音视频