多态性,称父母的子方法

时间:2016-09-12 11:24:07

标签: c# inheritance unity3d polymorphism

大家好我在使用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;
}

1 个答案:

答案 0 :(得分:2)

您无法致电SoldierPlayer.x.Gun();,因为SoldierPlayer.x的类型Base没有方法Gun()。 OOP世界和C#可以为您提供多种解决方案,您的选择取决于您的目标。

其中一些(按最佳做法排序):

1)覆盖多态。将 Gun()方法添加到 Base 类,并在派生类中实现它。例如

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) is-cast

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
}