2
public abstract class State
{
public virtual Enter(/* THIS NEED A PARAMETER */)
{
// an empty method
}
}

public class PlayerState : State
{
public override Enter(Player pl)
{
// method implementation
}
}

public class GoalkeeperState : State
{
public override Enter(Goalkeeper gk)
{
// method implementation
}
}

//EXAMPLE OF USE
public State globalState;
globalState.Enter(owner);
// OWNER CAN BE PLAYER OR GOALKEEPER

我知道虚拟方法和覆盖方法需要具有相同的“打印”。所以这里有一个设计缺陷。这样的事情也是可能的。我怎样才能做到这一点 ?你会怎么做?

4

2 回答 2

6

您可以在此处使用泛型:

public abstract class State<T>
{
    public virtual Enter(T item)
    {
        // an empty method
    }
}

public class PlayerState : State<Player>
{
    public override Enter(Player pl)
    {
        // method implementation
    }
}

public class GoalkeeperState : State<Goalkeeper>
{
    public override Enter(Goalkeeper gk)
    {
        // method implementation
    }
}
于 2013-03-25T11:24:33.690 回答
0

你可以定义

public override Enter(State pl)

或者,但我不确定我是否理解您想要正确执行的操作,如下所示:

public class Player
{
    public virtual Enter() {}
}

public class GoalKeeper : Player
{
    public override Enter() {}
}


public class State
{
    public List<Player> players {get; private set;}

    public State() { players = new List<Player(); }
}
于 2013-03-25T11:27:13.247 回答