成员隐藏
在派生类中通过 new关键字 实现成员隐藏
当子类方法名与父类方法名一致且父类方法没有virtual、abstract、override修饰时,要使用方法隐藏使子类型通过定义方法隐藏了父类继承到的旧方法。
隐藏和重写方法的区别:
- 如果方法是被隐藏的, 则根据引用类型来调用方法; 如果方法是被重写的, 则根据对象的实际类型来调用方法。更直观一点的说,使用方法隐藏后调用父类的同名方法有 父 a= new 父 和 父 a = new 子,调用子类方法仅有一种 子类 a = new 子;而使用重写方法后调用父类同名方法仅有一种 父 a = new 父,调用子类方法有 父 a = new 子 和 子 a = new 子。
- 如果想重写方法,需要对方法用virtual和override修饰; 如果想隐藏方法, 需要在子类中的方法用new修饰. (显然这个new和在创造对象时所用的new含义不一样)
如果子类和基类中含有同名(一模一样)的方法(方法体不一定一样, 只是函数头一模一样), 默认情况下是隐藏而不是被重写.
Humanoid 类
public class Humanoid
{
//Yell 方法的基版本
public void Yell()
{
Debug.Log ("Humanoid version of the Yell() method");
}
}
Enemy 类
public class Enemy : Humanoid
{
//new 关键字会隐藏 Humanoid 版本。
new public void Yell()
{
Debug.Log ("Enemy version of the Yell() method");
}
}
Orc 类
public class Orc : Enemy
{
//这会隐藏 Enemy 版本。
new public void Yell()
{
Debug.Log ("Orc version of the Yell() method");
}
}
WarBand 类
public class WarBand : MonoBehaviour
{
void Start ()
{
Humanoid human = new Humanoid();
Humanoid enemy = new Enemy();
Humanoid orc = new Orc();
//注意每个 Humanoid 变量如何包含对继承层级视图中不同类的引用,
//但每个变量都调用 Humanoid Yell() 方法。
human.Yell();
enemy.Yell();
orc.Yell();
}
}
成员重写
三种方法可以重写:
abstract抽象方法:在抽象类中出现,子类必须重写,除非子类也是抽象类
- virtual虚方法:修饰已经实现的方法,表示一个可以在子类重写的方法
- override重写方法:已经复写的方法,在子类可以继续重写,除非标识为sealed(sealed密封:1.在类的定义上只是当前类不能做父类 2.用在重写成员标识不能再次重写)