C#中类关系树的继承?

时间:2016-10-25 10:15:30

标签: c# oop generics inheritance composition

我们正在开发一款拥有多种游戏模式的游戏。我们在这里有以下代码:

// The following will be in our company's code base.

public class GameMode
{
    public GameState currentState;

    public List<GamePlayer> players;
}

public class GameState
{
    public GameMode gameMode;
}

public class GamePlayer
{
    public GameMode gameMode;
}

// The following will be in our game's code base.

public class Deathmatch : GameMode
{
    // Here, we've got a currentState of type GameState, NOT DeathmatchState
    // and a list of type of GamePlayer, NOT DeathmatchPlayer
}

public class DeathmatchState : GameState
{
    // GameMode here, not Deathmatch
}

public class DeathmatchPlayer : GamePlayer
{
    // GameMode here, not Deathmatch
}

对于上面的代码,我们遇到了一个基本类型字段而不是相应的继承类型的问题。所以我们去做了:

public class GameMode<TGameMode, TGameState, TGamePlayer>
    where TGameMode : GameMode<TGameMode, TGameState, TGamePlayer>
    where TGameState : GameState<TGameMode, TGameState, TGamePlayer>
    where TGamePlayer : GamePlayer<TGameMode, TGameState, TGamePlayer>
{
    public TGameState currentState;

    public List<TGamePlayer> players;
}

public class GameState<TGameMode, TGameState, TGamePlayer>
    where TGameMode : GameMode<TGameMode, TGameState, TGamePlayer>
    where TGameState : GameState<TGameMode, TGameState, TGamePlayer>
    where TGamePlayer : GamePlayer<TGameMode, TGameState, TGamePlayer>
{
    public TGameMode gameMode;
}

public class GamePlayer<TGameMode, TGameState, TGamePlayer>
    where TGameMode : GameMode<TGameMode, TGameState, TGamePlayer>
    where TGameState : GameState<TGameMode, TGameState, TGamePlayer>
    where TGamePlayer : GamePlayer<TGameMode, TGameState, TGamePlayer>
{
    public TGameMode gameMode;
}


//--------------------------------------------------------------------------------------


public class Deathmatch : GameMode<Deathmatch, DeathmatchState, DeathmatchPlayer>
{
    // Here, we've got the currentState of type TGameState, which is exactly DeathmatchState
    // and a list of TGamePlayer, which is exactly DeathmatchPlayer
}

public class DeathmatchState : GameState<Deathmatch, DeathmatchState, DeathmatchPlayer>
{
    // Deathmatch here
}

public class DeathmatchPlayer : GamePlayer<Deathmatch, DeathmatchState, DeathmatchPlayer>
{
    // Deathmatch here
}

虽然这实际上是完美的,但这是唯一的方法吗?或者还有其他方法可以减少与其他程序员的混淆吗?

对于这种方法,我们实际上是在一个维度上使用继承(Game-Deathmatch关系),在另一个维度上使用泛型(GameMode-GameState-GamePlayer关系)。

此外,我想了解其他语言如何应对这种情况:-P

0 个答案:

没有答案