我已经增强了这个答案,为您提供更全面的解决方案,并具有更好的语义语法。
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 (T)attributes[0];
}
// 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 上创建了一对扩展方法,让您可以做您正在寻找的事情。我稍微增强了您的代码Enum
,以使用.DisplayAttribute
System.ComponentModel.DataAnnotations
using System.ComponentModel.DataAnnotations;
public enum Days {
[Display(Name = "Sunday")]
Sun,
[Display(Name = "Monday")]
Mon,
[Display(Name = "Tuesday")]
Tue,
[Display(Name = "Wednesday")]
Wed,
[Display(Name = "Thursday")]
Thu,
[Display(Name = "Friday")]
Fri,
[Display(Name = "Saturday")]
Sat
}
要使用上述扩展方法,您现在只需调用以下代码:
Console.WriteLine(Days.Mon.ToName());
或者
var day = Days.Mon;
Console.WriteLine(day.ToName());