特性的简单实用!
Program.cs
class Program { static void Main(string[] args) { Console.WriteLine(PersonOptions.PersonOne.ToString() + " : " + PersonOptions.PersonOne.GetDescription()); Console.WriteLine(PersonOptions.PersonTwo.ToString() + " : " + PersonOptions.PersonTwo.GetDescription()); Console.WriteLine(PersonOptions.PersonThree.ToString() + " : " + PersonOptions.PersonThree.GetDescription()); Console.ReadLine(); } }
PersonOptions.cs
public enum PersonOptions { [Description("张三")] PersonOne, [Description("李四")] PersonTwo, [Description("王五")] PersonThree }
DescriptionAttribute.cs
public class DescriptionAttribute : Attribute { public string Description { get; set; } public DescriptionAttribute(string description) { this.Description = description; } }
EnumHelper.cs 扩展方法和反射的使用来获得Description.
public static class EnumHelper { public static string GetDescription(this Enum option) { string description = ""; FieldInfo fieldInfo = option.GetType().GetField(option.ToString()); var enumOption = (DescriptionAttribute)fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute)); if (enumOption != null) { description = enumOption.Description; } return description; } }
时间: 2024-10-11 16:35:33