簡體   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