这可能是最好的例子。我有一个属性的枚举:任何人都知道快速获取枚举值的自定义属性的方法吗?
public enum MyEnum {
[CustomInfo("This is a custom attrib")]
None = 0,
[CustomInfo("This is another attrib")]
ValueA,
[CustomInfo("This has an extra flag", AllowSomething = true)]
ValueB,
}
我想从一个实例的属性:
public CustomInfoAttribute GetInfo(MyEnum enumInput) {
Type typeOfEnum = enumInput.GetType(); //this will be typeof(MyEnum)
//here is the problem, GetField takes a string
// the .ToString() on enums is very slow
FieldInfo fi = typeOfEnum.GetField(enumInput.ToString());
//get the attribute from the field
return fi.GetCustomAttributes(typeof(CustomInfoAttribute ), false).
FirstOrDefault() //Linq method to get first or null
as CustomInfoAttribute; //use as operator to convert
}
由于这是使用反射我期待一些缓慢,但它似乎杂乱枚举转换当我已经拥有它的一个实例的时候,这个值就是一个字符串(它反映了名字)。
有没有人有更好的方法?
你和Enum.GetName()比较了吗? – 2008-08-20 12:41:06