Questo probabilmente è meglio mostrato con un esempio. Ho un enum con gli attributi:Qualcuno conosce un modo rapido per ottenere attributi personalizzati su un valore enum?
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,
}
voglio arrivare a quegli attributi di un'istanza:
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
}
come questo è utilizzando la riflessione mi aspetto una certa lentezza, ma sembra disordinato per convertire l'enum valore a una stringa (che riflette il nome) quando ne ho già un'istanza.
Qualcuno ha un modo migliore?
Hai confrontato con 'Enum.GetName()'? –