C#中new和override的区别

时间:2023-03-08 20:07:05
  • override是指“覆盖”,是指子类覆盖了父类的方法。子类的对象无法再访问父类中的该方法。(签名必须相同)
  • new是指“隐藏”,是指子类隐藏了父类的方法,当然,通过一定的转换,可以在子类的对象中访问父类的方法。
  • 以下代码的运行结果是什么?

    //

    1. class Base
    2. {
    3. public virtual void F1()
    4. {
    5. Console.WriteLine("Base's virtual function F1");
    6. }
    7. public virtual void F2()
    8. {
    9. Console.WriteLine("Base's virtual fucntion F2");
    10. }
    11. }
    12. class Derived:Base
    13. {
    14. public override void F1()
    15. {
    16. Console.WriteLine("Derived's override function F1");
    17. }
    18. public new void F2()
    19. {
    20. Console.WriteLine("Derived's new function F2");
    21. }
    22. }
    23. class Program
    24. {
    25. public static void Main(string[] args)
    26. {
    27. Base b1 = new Derived();
    28. //由于子类覆盖了父类的方法,因此这里调用的是子类的F1方法。也是OO中多态的体现
    29. b1.F1();
    30. //由于在子类中用new隐藏了父类的方法,因此这里是调用了隐藏的父类方法
    31. b1.F2();
    32. }
    33. }

    或者我们用以下的代码更加容易明白:

    1. class Program
    2. {
    3. public static void Main(string[] args)
    4. {
    5. Derived b1 = new Derived();
    6. //由于子类覆盖了父类的方法,因此这里调用的是子类的F1方法。也是OO中多态的体现
    7. ((Base) b1).F1();
    8. //由于在子类中用new隐藏了父类的方法,因此这里是调用了隐藏的父类方法
    9. ((Base) b1).F2();
    10. }
    11. }

    以上两个的输出都为:

    Derived's override function F1

    Base's virtual fucntion F2

    在上面的例子中,由于F1覆盖(override)了原先的方法,因此即使转成父类的对象,仍旧调用了子类的F1方法。而由于子类的F2方法只是“隐藏”了父类的F2方法,因此当强制转换成父类(Base)的对象去调用F2方法时,调用了原先隐藏的父类的F2方法。