voglio aggiungere un'altra soluzione: nel mio caso, ho bisogno di utilizzare un gruppo di Enum in un menu a discesa voci di elenco tasto. Così si potrebbero avere spazio, vale a dire più utenti descrizioni amichevole necessaria:
public enum CancelReasonsEnum
{
[Description("In rush")]
InRush,
[Description("Need more coffee")]
NeedMoreCoffee,
[Description("Call me back in 5 minutes!")]
In5Minutes
}
In una classe di supporto (HelperMethods) ho creato il seguente metodo:
public static List<string> GetListOfDescription<T>() where T : struct
{
Type t = typeof(T);
return !t.IsEnum ? null : Enum.GetValues(t).Cast<Enum>().Select(x => x.GetDescription()).ToList();
}
Quando si chiama questo helper si otterrà la lista delle descrizioni degli articoli.
List<string> items = HelperMethods.GetListOfDescription<CancelReasonEnum>();
AGGIUNTA: In ogni caso, se si desidera implementare questo metodo è necessario: estensione GetDescription per enum. Questo è quello che uso.
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =Attribute.GetCustomAttribute(field,typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return null;
/* how to use
MyEnum x = MyEnum.NeedMoreCoffee;
string description = x.GetDescription();
*/
}
Hai appena fatto questa domanda così potresti rispondere da solo? – juharr
Hai il permesso di chiedere e rispondere alla tua stessa domanda. la mia preoccupazione sarebbe che questa è una domanda doppia in ogni caso –
avrebbe dovuto essere Wiki! –