繁体   English   中英

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

[英]How to use an interface between classes and derived classes?

我目前正在尝试制作国际象棋游戏,并试图实现一个界面,但我无法访问界面。

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列表: 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,但基类是无关紧要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM