[英]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);
两种可能性:
您可能希望在ChessPiece类中实现该接口 - 由于接口名称,它对我更有意义。 如果需要在派生类中实现该方法,则将其设置为抽象方法。
获取实现界面的所有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.