2017-04-03 85 views
-2

Picture of Program DesignC#操作/類

我必須設計一個這樣操作的程序。我已經完成了機器人運動的基本代碼,但是方向要求我使用帶有顯示方法的「Action」類。

添加一個名爲Action的新類,它將公開以下幾條數據:

1)操作類型 2.)方向 3.)距離 3.)顯示()

öAction類的顯示方法應該發射RobotDirection.X其中X是用於全名方向

或MoveRobot(X)其中X是選定的距離。 o添加一個Action類型的列表,以跟蹤用戶輸入的方向和移動指令

o添加一個列表框,併爲動作列表中的每個項目調用Display()方法並將該信息添加到在 列表框

截至目前,我有一個枚舉類爲:

public enum ActionType 
{ 
    Movement, 
    Direction 
} 
public enum RobotDirection 
{ 
    North, 
    South, 
    East, 
    West 
} 

在我的動作類:

public String Display(Action x) 
    { 
     String robotAction = null; 

     if(x.ActionType == ActionType.Direction) 
     { 
      if(x.Direction == RobotDirection.North) 
      { 
       robotAction = "RobotDirection.North"; 
      } 
      else if(x.Direction == RobotDirection.East) 
      { 
       robotAction = "RobotDirection.East"; 
      } 
      else if(x.Direction == RobotDirection.South) 
      { 
       robotAction = "RobotDirection.South"; 
      } 
      else if(x.Direction == RobotDirection.West) 
      { 
       robotAction = "RobotDirection.West"; 
      } 

     } 

     else if (x.ActionType == ActionType.Movement) 
     { 
      robotAction = "MoveRobot(" + Distance + ")"; 
     } 

     return robotAction; 

    } 
} 

我將如何調用顯示方法來填充列表框?

謝謝!

+3

對不起,但我沒有看到您的文章中的問題/問題是什麼。 – Tatranskymedved

+0

我的問題是我不明白如何正確使用Display方法來填充列表框。雖然我有Display方法,但沒有將它連接到Listbox,我不確定x。在這種情況下代表。 – Yahtzee

+0

@ user7200174你見過[ListBox.ObjectCollection.Add方法]的文檔(https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.objectcollection.add(v = vs 0.110)的.aspx)? – PJvG

回答

0

您的Action類的問題在於您需要構造函數和字段,並且您不需要將Action作爲參數傳遞給Display方法。

首先添加一些字段您Action類:

public class Action 
{ 
    private ActionType type; 
    private RobotDirection direction; 
    private int distance; 

接下來,在你的類添加一個構造函數:

public Action(ActionType type, RobotDirection direction, int distance) 
    { 
     this.type = type; 
     this.direction = direction; 
     this.distance = distance; 
    } 

可以調用此構造函數創建一個新的Action對象如下:您可以在您的中使用this.typethis.direction 210方法,並且您也不需要任何參數用於您的Display方法(即, Display()而不是Display(Action x))。

您可能感興趣的最後一件事:InheritanceInterfaces。您可以創建新的類,例如MovementActionRotateAction,並使它們實現爲IAction,這將成爲僅包含Display()方法的接口。

MovementAction類將只包含ActionType typeint distance的字段。 RotateAction類將只包含ActionType typeRobotDirection direction的字段。他們都將以不同的方式實施Display()方法。

0

你應該調用此方法將字符串:

string specificAction = Display(/*any action*/) 

然後將字符串添加到您的列表框:

yourListBox.Items.Add(specificAction) 

希望它幫助!

+0

該問題陳述如下:「添加一個Action類型的列表以跟蹤由用戶輸入的方向和移動指令」。你的答案不包括那個,但我同意你的解決方案是正確的,如果這個'List '沒有用於除了記錄輸入動作之外的任何事情,因爲在這種情況下,這個列表是相當無用的。 – PJvG