CSharp虚拟方法和参数
本文关键字:参数 方法 虚拟 CSharp | 更新日期: 2023-09-27 18:05:35
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
我理解,虚拟和覆盖的方法需要有相同的"打印"。所以这里有一个设计缺陷。这样的事情有可能发生吗?我该怎么做呢?你会怎么做呢?
你可以在这里使用泛型:
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
}
}
你可以定义
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(); }
}