通过基类函数后是否可以获得修改后的参数值?

时间:2018-12-05 02:57:32

标签: c# unity3d

是否可能会造成儿童伤害打印5而不是10? 还是我必须在这里使用ref关键字?

谢谢。

这是我的基础课

public class DemoInheritance : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            float damage = 10;
            OnTakeDamage(damage);
        }
    }

    public virtual void OnTakeDamage(float damage)
    {
        Debug.Log("Base Damage: " + damage);
        damage -= 5;
        Debug.Log("New Damage: " + damage);
    }
}

我继承的课程

public class DemoInheritanceChild : DemoInheritance
{
    public override void OnTakeDamage(float damage)
    {
        base.OnTakeDamage(damage);
        Debug.Log("Child Damage: " + damage);
    }
}

2 个答案:

答案 0 :(得分:1)

有几种方法可以获取修改后的数据。您可以使函数返回操作变量的结果,或者您可以可以仅使用ref关键字,但是我认为{{3} },并建议您完全避免这种情况。

相反,我建议将公开公开的类方法与类覆盖其行为的能力分开:

public class DemoInheritance : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            float damage = 10;
            OnTakeDamage(damage);
        }
    }

    public void OnTakeDamage(float damage)
    {
        Debug.Log("Base Damage: " + damage);
        damage -= 5;
        Debug.Log("New Damage: " + damage);

        PostDamageResolved(damage);
    }

    protected virtual void PostDamageResolved(float postResolutionDamage);
}

public class DemoInheritanceChild : DemoInheritance
{
    protected override void PostDamageResolved(float postResolutionDamage)
    {
        Debug.Log("Child Damage: " + postResolutionDamage);
    }
}

此外,如果在基类中仅将OnTakeDamage称为购买Update(),则不应将其称为public

public class DemoInheritance : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            float damage = 10;
            OnTakeDamage(damage);
        }
    }

    private void OnTakeDamage(float damage)
    {
        Debug.Log("Base Damage: " + damage);
        damage -= 5;
        Debug.Log("New Damage: " + damage);
        PostDamageResolved(damage);
    }

    protected virtual void PostDamageResolved(float postResolutionDamage);
}

public class DemoInheritanceChild : DemoInheritance
{
    protected override void PostDamageResolved(float postResolutionDamage)
    {
        Debug.Log("Child Damage: " + postResolutionDamage);
    }
}

答案 1 :(得分:-1)

u不需要使用ref作为关键字,它将像这样

public class DemoInheritanceChild : DemoInheritance
{
    public override void OnTakeDamage(float damage)
    {
        base.OnTakeDamage(damage);
        Debug.Log("Child Damage: " + damage);
    }
}