多态性,调用父项的子方法

本文关键字:子方法 调用 多态性 | 更新日期: 2023-09-27 18:06:41

大家好,我正在使用 C# 在 Unity3d 中编程,当我编写代码时,我偶然遇到了一个小问题,我给你写了一个示例,因为我不知道解释我。

class Base
{
    public string name;
}
class Derived : Base
{
    public void Gun();
}
class BasePlayer
{
    public Base x;
}
class SoldierPlayer : BasePlayer
{ 
}

情况是这样的,我想做这样的事情

SoldierPlayer.x.Gun();

但我不知道该怎么做

真实案例是这样的

 public class BasePlayerController : MonoBehaviour
        {
            public BasePlayerManager playerManager; 
...
public class RobotPlayerController : BasePlayerController {
...
playerManager = gameObject.AddComponent<RobotPlayerManager>();

我将使用新方法

更新 1

我做得更好,我想在Base Controller manager.user.energy中做,并被视为下一个类型RobotManager.RobotUser.energy

BaseController
BaseManager
BaseUser
class BaseController
{
    BaseManager manager;
    public virtual void Move(int x,int y)...
}
class BaseManager {
    BaseUser user;
    public virtual Pause(bool state);
}
class BaseUser {
    int life
}
RobotController
RobotManager
RobotUser
class RobotController : BaseController
{
    // manager as RobotManager?
    public void Ray(int x,int y);
}
class RobotManager : BaseManager
{
    // user as RobotUser?
}
class RobotUser : BaseUser 
{
    int energy;
}

更新 2我寻求这样做

public Run()
{
    RobotController rc = new RobotController();
    rc.manager.energy;
}

多态性,调用父项的子方法

你不能调用SoldierPlayer.x.Gun();,因为SoldierPlayer.x的类型Base没有方法Gun((。OOP世界和C#可以为你提供很多解决方案,你的选择取决于你的目标。

其中一些(按最佳实践排序(:

1(覆盖多态性。 加。Gun(( 方法到类并将其嵌入派生类中。例如

class Base
{
    public string name;
    public void virtual Gun()
    {
        Trace.Log("I'm base class, i can't do anything");
    }
}
class Derived : Base
{
    public override void Gun()
    {
        Consule.WriteLine("Hello i have gun");
    }
}
class Derived2 : Base
{
    public override void Gun()
    {
        Consule.WriteLine("Hello i have 2 guns");
    }
}

2(重载多态性 在许多来源中,这种方法被提及为某种多态性 AD-HOC

public void GunAction(Derived2 o)
{
    o.Gun();
}
public void GunAction(Derived1 o)
{
    o.Gun();
}
public void GunAction(Base o)
{
    Trace.Log("I'm base class, i can't do anything");
}

3( 投射

public void GunAction(Base o)
{
    if(o is Derived1 )
        o.Gun();
    if(o is Derived2 )
        o.Gun();
}

更新 1 响应您的新要求

class BaseController
{
    public BaseManager manager;
...
class RobotController1 : BaseController
{
    // manager as RobotManager? - no it is stil BaseManager
    public void Ray(int x,int y);
}

class RobotController2 : BaseController
{
    // manager as RobotManager? - yes. now it is RobotManager 
    public void Ray(int x,int y);
    public RobotController2()
    {
        manager = new RobotManager();
    }
}
public void Run()
{
    var controller = new RobotController2();// you have RobotManager 
    controller.manager = new BaseManager();// it is again BaseManager
}