我有多个枚举,它们都具有相同的构造函数和属性,如下所示:
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;
}
}
答案 0 :(得分:3)
你必须将它们结合起来(或者如果这不是一个好主意,那就不是)
enum Enum1 {
A(1,2),
B(3,4),
C(6,7),
D(8,9);
答案 1 :(得分:1)
答案 2 :(得分:1)
枚举扩展枚举。他们也不能扩展别的东西。但是,他们可以实现接口。
你可以让它们都实现一个通用接口,并在接口上放置你的getA(),getB()方法。
答案 3 :(得分:0)
您可以尝试使用此功能,然后在枚举中添加标记:
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
`