[英]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.