我在这里合并了几个答案,以创建一个更具扩展性的解决方案。我提供它是为了以防将来对其他人有帮助。原始张贴在这里。
using System;
using System.ComponentModel;
public static class EnumExtensions {
// This extension method is broken out so you can use a similar pattern with
// other MetaData elements in the future. This is your base method for each.
public static T GetAttribute<T>(this Enum value) where T : Attribute {
var type = value.GetType();
var memberInfo = type.GetMember(value.ToString());
var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
return attributes.Length > 0
? (T)attributes[0]
: null;
}
// This method creates a specific call to the above method, requesting the
// Description MetaData attribute.
public static string ToName(this Enum value) {
var attribute = value.GetAttribute<DescriptionAttribute>();
return attribute == null ? value.ToString() : attribute.Description;
}
}
此解决方案在Enum上创建一对扩展方法。第一个允许您使用反射来检索与您的值关联的任何属性。第二个专门调用检索DescriptionAttribute
并返回其Description
值。
例如,考虑使用DescriptionAttribute
来自System.ComponentModel
using System.ComponentModel;
public enum Days {
[Description("Sunday")]
Sun,
[Description("Monday")]
Mon,
[Description("Tuesday")]
Tue,
[Description("Wednesday")]
Wed,
[Description("Thursday")]
Thu,
[Description("Friday")]
Fri,
[Description("Saturday")]
Sat
}
要使用上述扩展方法,您现在只需调用以下命令:
Console.WriteLine(Days.Mon.ToName());
要么
var day = Days.Mon;
Console.WriteLine(day.ToName());