从继承类添加到父类中的方法

Aug*_*ugs 1 c# inheritance

假设父类中有一个函数,它执行 x 和 y。但现在在继承的类中,您想让该函数也执行 z 操作。您不能覆盖它,因为这意味着该函数不再执行 x 和 y。

这是我的统一示例:

这是父类中的代码:

protected virtual void Start () 
{
    MyRigidBody = gameObject.GetComponent<Rigidbody>();
    if(Controls.Length < 4)
        throw new System.Exception("Controls not assigned correctly");
}
Run Code Online (Sandbox Code Playgroud)

现在我想做这样的事情:

protected void Start () 
{
    MyBase.Start();//MyBase.Start doesn't work
    BlahBlahBlah();
    Stuff();
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Jak*_*rtz 5

您可以使用base来调用 的基类的实现Start()。您还必须使用子类中的方法overridevirtual

protected override void Start () 
{
    base.Start();
    BlahBlahBlah();
    Stuff();
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用模板方法模式在基类中定义方法的骨架,并在派生类中提供某些部分的实现。

public void Start() 
{
    MyRigidBody = gameObject.GetComponent<Rigidbody>();
    if(Controls.Length < 4)
        throw new System.Exception("Controls not assigned correctly");

    DoSomethingElse();
}

protected virtual void DoSomethingElse()
{
    //can be empty in base class, derived classes provide the implementation
}
Run Code Online (Sandbox Code Playgroud)

Start方法不是虚拟的。如果要修改Start派生类中方法的行为,可以重写DoSomethingElse().