我有兩種移動物體——盒子和汽車——它們的移動方式有點不同。
Box:設定為向右、向左、向上或向下移動時,將向所需方向移動 1 個像素。
汽車:當設定為向右或向左移動時 - 將順時針/逆時針旋轉。當設定為向前/向后移動時 - 將根據汽車的正面和背面移動。因此,如果汽車旋轉 45 度并且我們將其設定為向前移動,汽車將向右移動半像素,向上移動半像素(假設汽車正面朝上)。
我想知道以下哪種方法更好,或者是否有更好的方法:
public abstract class MovingObject
{
public abstract void Move();
public enum Direction { UP, DOWN, LEFT, RIGHT, FORWARD, BACKWARD }
public Direction CurrentDirection { get; set; }
//some other fields and properties
public class Box : MovingObject
{
public override void Move(){...}
//some Box related things
}
public class Car : MovingObject
{
public override void Move(){...}
//some Car related things
}
}
public abstract class MovingObject
{
public abstract void Move();
//some fields and properties
public class Box : MovingObject
{
public enum Direction { UP, DOWN, LEFT, RIGHT }
public Direction CurrentDirection { get; set; }
public override void Move(){...}
}
public class Car : MovingObject
{
public enum Direction { FORWARD, BACKWARD, LEFT, RIGHT }
public Direction CurrentDirection { get; set; }
public override void Move(){...}
}
}
uj5u.com熱心網友回復:
我建議創建兩個列舉和一個需要列舉的通用基類,代碼如下所示。
public enum BoxDirection
{
UP,
DOWN,
LEFT,
RIGHT
}
public enum CarDirection
{
LEFT,
RIGHT,
FORWARD,
BACKWARD
}
public abstract class MovingObject<T> where T: Enum
{
public abstract void Move();
public T CurrentDirection { get; set; }
//some other fields and properties
public class Box : MovingObject<BoxDirection>
{
public override void Move() { ... }
//some Box related things
}
public class Car : MovingObject<CarDirection>
{
public override void Move() { ... }
//some Car related things
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/494850.html
上一篇:如何將變數傳遞給基類
