C# 如何正确编码可重用 类?

C# how to properly code reusable classes?

我希望能够从 GameState 对象调用方法,如下所示:

public void some_method (GameState s)
{
  GameState s_copy = s.duplicate()
  s_copy.make_move()
  //s_copy now has made a move, but s remains untouched.
}

所以 class GameState 应该有:

-make_move方法。

-复制方法。 Duplicate 用于创建对象的深拷贝,这样我就可以在 GameState 中移动而不改变原始状态。

这让我相信我需要创建一个界面,因为我可以有多个游戏。这是我感到困惑的地方。我目前正在尝试:

public interface IGameState
{
  void make_move();
  GameState duplicate();
}
public class GameState : IGameState
{
  public virtual void make_move(){}
  public virtual GameState duplicate(){}
}
public class Game1 : GameState
{
  public override void make_move(){ /*whatever a move is in game 1*/}
  public GameState override duplicate() { /*deepcopy of the class variables*/ }
}
public class Game2 : GameState
{
  public void make_move(){ /*whatever a move is in game 2*/}
  GameState duplicate() { /*deepcopy of the class variables*/ }
}

因此,当我调用“some_method”时,我希望能够传递任何游戏对象:

g1 = new Game1();
g2 = new Game2();
some_method((GameState)g1);
some_method((GameState)g2);

但我似乎无法访问这些方法,并且在使用新创建的 GameState 时,duplicate() GameState 键入会造成混乱。 我读过有关泛型、静态、抽象 classes 和接口的内容,但无法理解应该如何完成,到目前为止感觉不对。

编辑:Game1 和 Game2 是完全不同的游戏:比如说 othello 和 tictactoe

您不想在游戏之间更改 GameState 对象。 因此,为每个游戏创建一个 GameState 对象,前提是每个游戏共享相同的游戏状态定义。

public class GameState
{
  public string State {get;set;} = ""
}

public class Game {
  private readonly GameState state;
  public Game(GameState state) {
    this.state = state;
  }

  public void Play() {
     state = "Game is Starting";
  }

}

var g1 = new Game(new GameState() { State = "Game1State" });
var g2 = new Game(new GameState() { State = "Game2State" });
g1.Play();

我认为您可以通过应用一些小的更改来解决您的问题:

public interface IGameState
{
  // Just Naming Conventions here
  void MakeMove();
  IGameState Duplicate();
}

// Get rid of GameState class

public class Game1 : IGameState // implement the interface
{
  public void MakeMove(){ /*whatever a move is in game 1*/}
  public IGameState Duplicate() { /*deepcopy of the class variables*/ }
}

// Game2 accordingly

// then `SomeMethod` should work like this:
public void SomeMethod (IGameState s)
{
  IGameState s_copy = s.Duplicate();
  s_copy.MakeMove();
  //s_copy now has made a move, but s remains untouched.
}

为了保留更改,您可能需要 return 变异状态:

public IGameState SomeMethod (IGameState s)
{
  IGameState s_copy = s.Duplicate();
  s_copy.MakeMove();
  return s_copy;
}