“扩展”枚举
我有多个枚举的所有具有相同的构造和属性,就像这样:“扩展”枚举
enum Enum1 {
A(1,2),
B(3,4);
public int a, b;
private Enum1(int a, int b) {
this.a = a;
this.b = b;
}
}
enum Enum2 {
C(6,7),
D(8,9);
public int a, b;
private Enum1(int a, int b) {
this.a = a;
this.b = b;
}
}
等等... 不幸的是Enum1和Enum2已经扩展Enum,所以不是可以写一个他们可以扩展的超类。 是否有另一种方法来归档?
更新:这里是一个“现实世界”的例子。想想一个经典的RPG,你有物品,盔甲,武器等,这些都会给你带来奖励。
enum Weapon {
SWORD(3,0,2),
AXE_OF_HEALTH(3,4,1);
// bonus for those weapons
public int strength, health, defense;
private Weapon(int strength, int health, int defense) {
this.strength = strength;
this.health = health;
this.defense = defense;
}
}
enum Armour {
SHIELD(3,1,6),
BOOTS(0,4,1);
// bonus
public int strength, health, defense;
private Weapon(int strength, int health, int defense) {
this.strength = strength;
this.health = health;
this.defense = defense;
}
}
枚举扩展枚举。他们不能再扩展别的东西。但是,他们可以实现接口。
您可以使它们都实现一个通用接口,并将getA(),getB()方法放在接口上。
你必须给他们(或不如果多数民众赞成不是一个好主意)结合
enum Enum1 {
A(1,2),
B(3,4),
C(6,7),
D(8,9);
对不起,但那些枚举仍然必须分开。 – user28061 2012-07-10 09:42:08
在这种情况下,你必须有一个Enum1,就像你现在有一个Enum1一样。为什么你不能有一个组合的枚举类型? – 2012-07-10 09:54:14
你可以尝试使用这个比添加标志,以您的枚举:
public class ExtendetFlags : Attribute
{
#region Properties
///
/// Holds the flagvalue for a value in an enum.
///
public string FlagValue { get; protected set; }
#endregion
#region Constructor
///
/// Constructor used to init a FlagValue Attribute
///
///
public ExtendetFlags(string value)
{
this.FlagValue = value;
}
#endregion
}
public static class ExtendetFlagsGet
{
///
/// Will get the string value for a given enums value, this will
/// only work if you assign the FlagValue attribute to
/// the items in your enum.
///
///
///
public static string GetFlagValue(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
ExtendetFlags[] attribs = fieldInfo.GetCustomAttributes(
typeof(ExtendetFlags), false) as ExtendetFlags[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].FlagValue : null;
}
}
使用很简单:
` [ExtendetFlags("test1")]
Application = 1,
[ExtendetFlags("test2")]
Service = 2
`
为什么你有独立的'Enum'类具有非常枚举相同的数据?为什么'C'或'D'不能进入'Enum1'?我认为给我们具体的情况可能有助于接近真正的解决方案。 – 2012-07-10 09:40:45
请参阅[Java扩展枚举](http://stackoverflow.com/questions/1414755/java-extend-enum)。 – Lion 2012-07-10 09:47:14
对不起,但这种设计看起来不正确。当然YMMV,但这些属性更好的“个人”盾牌,靴子等。我建议有“项目”有一个类型字段,而这又将是一个枚举*没有*属性。当然,还有其他方法可以做到这一点,但请将这些信息作为类属性的一部分(从配置驱动)提供,而不是让它们“硬编码”。 – 2012-07-10 09:54:41