如何在类和派生类之间使用接口

本文关键字:接口 之间 派生 | 更新日期: 2023-09-27 18:37:14

我目前正在尝试制作国际象棋游戏,并尝试实现一个接口,但是我无法访问该接口。

public interface IChessPiece
{
     bool CheckMove(int row, int col);
}
public class ChessPiece { ... }
public class Pawn : ChessPiece, IChessPiece
{
     public bool CheckMove(int row, int col) { ... }
}
public class ChessPieces {  public List<ChessPieces> chessPieces; ... }

我似乎无法访问CheckMove()方法。

board.chessPieces.Find(x => <condition>).CheckMove(row, col);

如何在类和派生类之间使用接口

你可以ChessPiece实现为抽象类

public interface IChessPiece {
  bool CheckMove(int row, int col);
}
// Note "abstract"
public abstract class ChessPiece: IChessPiece {
  ... 
  // Note "abstract"
  public abstract bool CheckMove(int row, int col);
}
// Pawn implements IChessPiece since it's derived form ChessPiece
public class Pawn: ChessPiece {
  // Actual implementation
  public override bool CheckMove(int row, int col) { ... }
}

你的类还需要实现IChessPiece接口,并且很可能让它abstract,因为它不应该直接实例化。然后,您应该将板上的List更改为IChessPiece类型:

public class ChessPiece : IChessPiece { ... }
public class Pawn : ChessPiece, IChessPiece
{
     public bool CheckMove(int row, int col) { ... }
}
public class ChessPieces {  public List<IChessPieces> chessPieces; ... }

ChessPiece类中实现IChessPiece

public class ChessPiece : IChessPiece { ... }

我似乎无法访问CheckMove()方法。

因为你知道ChessPieces实现了CheckMove,但编译器没有。

如果你不想IChessPiece接口实现到类ChessPiece那么你需要像

  ((IChessPiece)(board.chessPieces.Find(x => <condition>))).CheckMove(row, col);

两种可能性:

  1. 您可能希望在 ChessPiece 类中实现接口 - 由于接口名称,它对我来说更有意义。如果需要在派生类中实现该方法,请使其成为抽象方法。

  2. 获取实现接口的所有棋子的列表:ChessPieces.OfType<IChessPiece>

ChessPiece没有CheckMove方法。你可以这样做:

public abstract class ChessPiece : IChessPiece
{
    public abstract bool CheckMove(int row, int col);
}

这可确保从 ChessPiece 基类派生的任何人也必须实现 CheckMove 方法。任何派生自 ChessPiece 的类也将实现 IChessPiece。

public class Pawn : ChessPiece // implicitly also implements IChessPiece
{
    public override bool CheckMove(int row, int col) 
    {
    }
}

但是,接口的想法是,在使用它们时,实现应该无关紧要。因此,您的List<ChessPiece>实际上应该是一个List<IChessPiece> - 这实际上就足够了,因为添加到该列表中的任何项目都必须实现 IChessPiece,但基类无关紧要。