• C# new 和 override 的区别


    在C#中子类继承抽象类的时候,new 和override都可以用来修饰子类方法,但两者之间是有区别的。

    相同点:

    1. 它们都是子类在覆写基类方法时,修饰子类同名方法用的,都是为了隐藏基类的同名方法
    2. 在实例化子类对象的时候,访问的都是子类的方法
    3. 都可以在方法体中通过base来访问基类的方法

    不同点:

    1. override用于重写基类的virtual方法,必须要申明override关键字,而new可以省略
    2. override会覆盖掉基类的同名方法,除非是在子类方法中用base访问基类方法,除此以外,再也无法访问基类方法。而new还是可以用通过其它方法访问到基类方法

    怎么选择new还是override?

    1. 我们通常认为,基类的virtual方法是不完善的,只提供了基础的的申明和实现,override的方法,通常才是完善和可用,一般不希望去调用基类的虚方法,所以当我们只是需要这样简单的约定的时候,就会采用override的方式来覆写
    2. 什么时候用new?当基类的方法已经很完善,并且有可能在某种情况下需要调用的时候,我们就用new,这个时候new只是作为一种隐藏基类的方法和对基类同名方法的进一步扩展,基类的方法同样是有意义并且可以被调用的

    下面是代码示例:

    1. using System;
    2. namespace TestNamespace
    3. {
    4. // 基类
    5. public abstract class BaseClass
    6. {
    7. public string DoSomething()
    8. {
    9. return "BaseClass.DoSomething()";
    10. }
    11. public virtual string DoSomething2()
    12. {
    13. return "BaseClass.DoSomething()2";
    14. }
    15. }
    16. // 子类
    17. public partial class ChildClass : BaseClass
    18. {
    19. public new string DoSomething()
    20. {
    21. return "ChildClass. DoSomething()";
    22. //return base.DoSomething();
    23. }
    24. public override string DoSomething2()
    25. {
    26. return "ChildClass. DoSomething()2";
    27. //return base.DoSomething2();
    28. }
    29. }
    30. }

    调用方法: 

    1. /
    2. ChildClass child = new ChildClass();
    3. child.DoSomething(); // 调用子类同名方法DoSomething()
    4. child.DoSomething2() // 调用子类同名方法DoSomething2()
    5. /
    6. BaseClass child = new ChildClass();
    7. child.DoSomething(); // 调用基类同名方法DoSomething()
    8. child.DoSomething2() // 调用子类同名方法DoSomething2()

    从上面的代码示例中可以发现,一旦基类的虚方法被override,我们就无法再访问基类的DoSomething()方法,除非是在子类方法中用base.DoSomething()去访问,但对于new修饰的子类同名方法,我们还是可以访问。

  • 相关阅读:
    React16.8新增特性Hooks--概念理解
    使用Vitis HLS生成 IP核 (verilog版和图形化版)
    Jedis操作Redis
    图像的表示方法
    CSS书写位置和基础选择器
    Flink不止于计算,存算一体才是未来
    飞书开发学习笔记(六)-网页应用免登
    Leetcode 381. Insert Delete GetRandom O(1) - Duplicates allowed (数据结构设计好题)
    Scala Intellij编译错误:idea报错xxxx“is already defined as”
    Spring整合Redis详细步骤
  • 原文地址:https://blog.csdn.net/m0_46635910/article/details/134432685