2014-09-24 87 views
0

存在着組裝一個枚舉:其他組件,屬性擴展Enum

public enum TheEnumeration 
{ 
    TheFirstValue = 1, 
    TheSecondValue = 2 
} 

在另一個大會,我想用一些屬性來擴展此枚舉(我知道這是不是有效的代碼,只是爲了顯示這個想法):

public enum MyExtendedEnumeration : TheEnumeration 
{ 
    [MyAttribute("The First Value")] 
    TheFirstValue, 

    [MyAttribute("The 2nd Value")] 
    TheSecondValue 
} 

有沒有一種方法可以正確實現這個目標?

+1

不是你想要的樣子 - 你不能擴展或從枚舉繼承。你打算如何使用該屬性? – 2014-09-24 13:54:25

+0

實際上,它看起來像你可能能夠使用標準的'DescriptionAttribute'' – Plutonix 2014-09-24 18:05:13

+0

@Plutonix如何能夠做到這一點與DescriptionAttribute,如果從基礎枚舉繼承是不可能的(根據現有的答案)?你能給我一個答案的例子嗎? – 2014-09-25 09:58:24

回答

1

你不能延伸枚舉,你不能從它們繼承。你可能只需要創建一個新的Enum,重複像通過一樣的值,然後裝飾你的。

public enum MyExtendedEnumeration 
{ 
    [MyAttribute("The First Value")] 
    TheFirstValue = TheEnumeration.TheFirstValue, 

    [MyAttribute("The 2nd Value")] 
    TheSecondValue = TheEnumeration.TheFirstValue 
} 

參見:Extending enums in c#

0

枚舉不能從另一個枚舉繼承。它們基於System.Enum 您可以將屬性放在成員上。

創建一個行爲有點像Enum的類/類型可能在這樣的場景中很有用。 假設您可以「改變」原始枚舉。

/// 
/// Sample of a STRING or non int based enum concept. 
/// 

public sealed class FilterOp { 
    private static readonly Dictionary<string, FilterOp> EnumDictionary = new Dictionary<string, FilterOp>(); 
    private readonly string _name; 
    private readonly string _value; 

    public const string Eq = "Eq"; 
    public const string Ne = "Ne"; 
    public const string Gt = "Gt"; 
    public const string Ge = "Ge"; 
    public const string Lt = "Lt"; 
    public const string Le = "Le"; 
    public const string And = "And"; 
    public const string Or = "Or"; 
    public const string Not = "Not"; 

    public static readonly FilterOp OpEq = new FilterOp(Eq); 
    public static readonly FilterOp OpNe = new FilterOp(Ne); 
    public static readonly FilterOp OpGt = new FilterOp(Gt); 
    public static readonly FilterOp OpGe = new FilterOp(Ge); 
    public static readonly FilterOp OpLt = new FilterOp(Lt); 
    public static readonly FilterOp OpLe = new FilterOp(Le); 
    public static readonly FilterOp OpAnd = new FilterOp(And); 
    public static readonly FilterOp OpOr = new FilterOp(Or); 
    public static readonly FilterOp OpNot = new FilterOp(Not); 


    private FilterOp(string name) { 
     // extend to cater for Name/value pair, where name and value are different 
     this._name = name; 
     this._value = name; 
     EnumDictionary[this._value] = this; 
    } 

    public override string ToString() { 
     return this._name; 
    } 

    public string Name { 
     get { return _name; } 
    } 

    public string Value { 
     get { return _value; } 
    } 

    public static explicit operator FilterOp(string str) { 
     FilterOp result; 
     if (EnumDictionary.TryGetValue(str, out result)) { 
      return result; 
     } 
     return null; 
    } 
}