CSharp虚拟方法和参数

时间:2013-03-25 11:22:56

标签: c# parameters virtual override

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

据我所知,virtual和overriden方法需要具有相同的“print”。所以这里有一个设计缺陷。所以这样的事情是可能的。我怎样才能做到这一点 ? 你会怎么做?

2 个答案:

答案 0 :(得分:5)

您可以在此处使用泛型:

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
    }
}

答案 1 :(得分: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(); }
}