扩展其他程序集中具有属性的枚举
本文关键字:属性 枚举 集中 其他 程序 程序集 扩展 | 更新日期: 2023-09-27 18:24:09
程序集中存在一个枚举:
public enum TheEnumeration
{
TheFirstValue = 1,
TheSecondValue = 2
}
在另一个程序集中,我想用一些属性来扩展这个枚举(我知道这不是有效的代码,只是为了展示这个想法):
public enum MyExtendedEnumeration : TheEnumeration
{
[MyAttribute("The First Value")]
TheFirstValue,
[MyAttribute("The 2nd Value")]
TheSecondValue
}
有没有办法以适当的方式实现这一目标?
不能扩展枚举,不能从中继承。您可能只需要创建一个新的枚举,它像传递一样重复值,然后装饰您的值。
public enum MyExtendedEnumeration
{
[MyAttribute("The First Value")]
TheFirstValue = TheEnumeration.TheFirstValue,
[MyAttribute("The 2nd Value")]
TheSecondValue = TheEnumeration.TheFirstValue
}
请参阅:在c#中扩展枚举
枚举不能从另一个枚举继承。它们基于System.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;
}
}