[英]C# Abstract Class having Abstract Variables
We have an abstract class called Game.我们有一个名为 Game 的抽象 class。
public abstract class Game
{
protected Player player;
public virtual void InitPlayer()
{
// steps
player = new Player(xxxxxxx);
}
// Other methods manipulating data from player.
}
and there are two child classes of Game, let's say GameA and GameB .并且有两个 Game 的子类,比如说GameA和GameB 。
public class GameA : Game
{
public override void InitPlayer()
{
base.InitPlayer();
}
}
However, Player Variable in Game Class is also Abstract, having PlayerGameA and PlayerGameB .然而,游戏 Class 中的玩家变量也是抽象的,有PlayerGameA和PlayerGameB 。
public abstract class Player
{
}
public class PlayerGameA : Player
{
}
Note that Player and PlayerGameA Constructors have same arguments.请注意, Player 和 PlayerGameA 构造函数具有相同的 arguments。
Now I have a problem about creating an instance of Abstract Class in InitPlayer Method.现在我有一个关于在 InitPlayer 方法中创建 Abstract Class 实例的问题。 The result what I want is unifying result when creating an instance of GameA and calling gameA.InitPlayer() will create playerGameA ,and still other methods from GameClass needs to be able to manipulate data from that player variable.
我想要的结果是在创建 GameA 的实例并调用 gameA.InitPlayer() 时统一结果将创建playerGameA ,而 GameClass 中的其他方法仍需要能够操作来自该玩家变量的数据。
You can take a number of approaches.您可以采取多种方法。 A straightforward one is to make your concrete sublclass of
Game
responsible for providing a concrete implementation of Player
, eg:一个简单的方法是让您的具体
Game
子类负责提供Player
的具体实现,例如:
public abstract class Game
{
protected Player player;
protected void InitPlayer(Player concretePlayer)
{
// steps
player = concretePlayer;
}
}
public class GameA : Game
{
public void InitPlayer()
{
base.InitPlayer(new PlayerGameA());
}
}
A better approach is to make Game
accept a generic parameter TPlayer
.更好的方法是让
Game
接受一个通用参数TPlayer
。
But you should place any non-generic functionality in a GameBase
non-generic class但是您应该将任何非通用功能放在
GameBase
非通用 class
public abstract class GameBase
{
// non generic functionality here
}
public abstract class Game<TPlayer> : GameBase where TPlayer : Player
{
protected TPlayer player;
protected void InitPlayer(TPlayer concretePlayer)
{
// steps
player = concretePlayer;
}
}
public class GameA : Game<PlayerGameA>
{
public void InitPlayer()
{
base.InitPlayer(new PlayerGameA());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.