在其他程序集中使用属性扩展枚举

时间:2014-09-24 13:51:22

标签: c# enums

汇编中存在枚举:

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

在另一个程序集中,我想用一些属性扩展这个枚举(我知道这不是有效的代码,只是为了表明这个想法):

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

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

有没有办法以正确的方式实现这一目标?

2 个答案:

答案 0 :(得分:1)

您无法扩展枚举,也无法继承它们。您可能只需要创建一个新的枚举,重复值,如通过,然后装饰你的。

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

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

请参阅:Extending enums in c#

答案 1 :(得分:0)

Enums无法从另一个Enum继承。它们基于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;
    }
}