我需要存储一个包含5个方向的数组,我想知道什么是最可读的方式。 我可以做阵列
int myDirection[100] = {0,1,2,3,4,5,4,4,3,4,0......etc // poor readability
或者我可以使用常量并执行
const up = 1;
const down = 2; //... etc
int myDirection[100] = {up, down, center, right, left, .....etc
或者我可以写一个结构
struct direction
{ private byte mydirectionval;
{
public void direction Setup(){mydirection =1;}
public void direction Setright(){mydirection=2;}
public void direction Setdown(){mydirection=3;}
public void direction Setleft(){mydirection=4;}
public void direction Setcenter(){mydirection=0;}
public direction Getdirection(){....
}
direction newpath[100] = { ......
或者我应该写一个班级
public static class direction // not sure use static here ?
{ private int direction =0;
public const int Up = 1;
public const int left =2;
public const int down = 3;
public const int right = 4;
public const int center = 0;
public int getdirection(){return direction}
public void int setdirection(int x){direction=x}
}
direction mydir[100] = new direction;
mydir[0].setdirection(up);
// or use it like
mydir[0]=mydir.up //==> i prefer readability of code so this looks better?
好的人sugest使用枚举,但后来我需要一个数组mydir [100]的枚举 该怎么做??
答案 0 :(得分:3)
使用enum。
enum Direction
{
up = 1,
down = 2,
center = 3,
right = 4,
left = 5
}
您可以在数组中使用它:
Direction[] myDirection = { Direction.left, Direction.up, Direction.right ... };
或
myDirection[0] = Direction.left; ...
答案 1 :(得分:0)
enum怎么样?
public enum Direction
{
up,
down,
right,
left,
center
}
使用它:
Direction.up;