参见英文答案 >
What’s the best way to implement `next` and `previous` on an enum type? 2个
我有一个Java的枚举如下:
public enum Cars
{
Sport,
SUV,
Coupe
}
我需要获得枚举的下一个值.所以,假设我有一个名为myCurrentCar的变量:
private Cars myCurrentCar = Cars.Sport;
我需要创建一个函数,在调用时将myCurrentCar的值设置为枚举中的下一个值.如果枚举不再有值,我应该将变量设置为枚举的第一个值.
我以这种方式开始实施:
public Cars GetNextCar(Cars e)
{
switch(e)
{
case Sport:
return SUV;
case SUV:
return Coupe;
case Coupe:
return Sport;
default:
throw new IndexOutOfRangeException();
}
}
这是有效的,但它是一个高维护功能,因为每次我修改枚举列表,我必须重构该功能.
有没有办法将枚举分割成一个字符串数组,获取下一个值并将字符串值转换为原始枚举?因此,如果我在数组的末尾,我只需抓住第一个索引