成员隐藏

在派生类中通过 new关键字 实现成员隐藏
当子类方法名与父类方法名一致且父类方法没有virtual、abstract、override修饰时,要使用方法隐藏使子类型通过定义方法隐藏了父类继承到的旧方法。

隐藏和重写方法的区别:

  • 如果方法是被隐藏的, 则根据引用类型来调用方法; 如果方法是被重写的, 则根据对象的实际类型来调用方法。更直观一点的说,使用方法隐藏后调用父类的同名方法有 父 a= new 父 和 父 a = new 子,调用子类方法仅有一种 子类 a = new 子;而使用重写方法后调用父类同名方法仅有一种 父 a = new 父,调用子类方法有 父 a = new 子 和 子 a = new 子。
  • 如果想重写方法,需要对方法用virtual和override修饰; 如果想隐藏方法, 需要在子类中的方法用new修饰. (显然这个new和在创造对象时所用的new含义不一样)
  • 如果子类和基类中含有同名(一模一样)的方法(方法体不一定一样, 只是函数头一模一样), 默认情况下是隐藏而不是被重写.

    Humanoid 类

    1. public class Humanoid
    2. {
    3. //Yell 方法的基版本
    4. public void Yell()
    5. {
    6. Debug.Log ("Humanoid version of the Yell() method");
    7. }
    8. }

    Enemy 类

    1. public class Enemy : Humanoid
    2. {
    3. //new 关键字会隐藏 Humanoid 版本。
    4. new public void Yell()
    5. {
    6. Debug.Log ("Enemy version of the Yell() method");
    7. }
    8. }

    Orc 类

    1. public class Orc : Enemy
    2. {
    3. //这会隐藏 Enemy 版本。
    4. new public void Yell()
    5. {
    6. Debug.Log ("Orc version of the Yell() method");
    7. }
    8. }

    WarBand 类

    1. public class WarBand : MonoBehaviour
    2. {
    3. void Start ()
    4. {
    5. Humanoid human = new Humanoid();
    6. Humanoid enemy = new Enemy();
    7. Humanoid orc = new Orc();
    8. //注意每个 Humanoid 变量如何包含对继承层级视图中不同类的引用,
    9. //但每个变量都调用 Humanoid Yell() 方法。
    10. human.Yell();
    11. enemy.Yell();
    12. orc.Yell();
    13. }
    14. }

    成员重写

    三种方法可以重写:

  • abstract抽象方法:在抽象类中出现,子类必须重写,除非子类也是抽象类

  • virtual虚方法:修饰已经实现的方法,表示一个可以在子类重写的方法
  • override重写方法:已经复写的方法,在子类可以继续重写,除非标识为sealed(sealed密封:1.在类的定义上只是当前类不能做父类 2.用在重写成员标识不能再次重写)