下面的手段是使用給枚舉項打標籤的方式,來返回字符串this
下面分別定義一個屬性類,和一個枚舉幫助類spa
- [AttributeUsage(AttributeTargets.Field,AllowMultiple = false)]
- public sealed class EnumDescriptionAttribute : Attribute
- {
- private string description;
- public string Description { get { return description; } }
-
- public EnumDescriptionAttribute(string description)
- : base()
- {
- this.description = description;
- }
- }
- public static class EnumHelper
- {
- public static string GetDescription(Enum value)
- {
- if (value == null)
- {
- throw new ArgumentException("value");
- }
- string description = value.ToString();
- var fieldInfo = value.GetType().GetField(description);
- var attributes =
- (EnumDescriptionAttribute[]) fieldInfo.GetCustomAttributes(typeof (EnumDescriptionAttribute), false);
- if (attributes != null && attributes.Length > 0)
- {
- description = attributes[0].Description;
- }
- return description;
- }
- }
使用舉例:.net
- enum Week
- {
- [EnumDescription("星期一")]
- Monday,
- [EnumDescription("星期二")]
- Tuesday
- }
-
- Console.WriteLine(EnuHelper.GetDescription(Week.Monday))