需求:我们想得到枚举上面的注释
1)枚举类
public enum Sex { /// <summary> /// 女 /// </summary> [CommonAttribute("女")] Woman = 0, /// <summary> /// 男 /// </summary> [CommonAttribute("男")] Man = 1, /// <summary> /// 其他 /// </summary> [CommonAttribute("其他")] Other = 2 }
2.特性类
public class CommonAttribute:Attribute { public string Remark { get; private set; } public CommonAttribute(string remark) { this.Remark = remark; } }
3.反射类(这里要引用反射 using System.Reflection;)
public class AttributeExtend { public static string GetRemark(Sex value) { Type type = value.GetType(); var field = type.GetField(value.ToString()); if (field.IsDefined(typeof(CommonAttribute), true)) { CommonAttribute attribute = (CommonAttribute)field.GetCustomAttribute(typeof(CommonAttribute), true); return attribute.Remark; } else { return value.ToString(); } } }
4.使用
static void Main(string[] args) { try { Console.WriteLine("Start"); Console.WriteLine(AttributeExtend.GetRemark(Sex.Man)); Console.WriteLine(AttributeExtend.GetRemark(Sex.Woman)); Console.WriteLine(AttributeExtend.GetRemark(Sex.Other)); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); }
标签:反射,额外,Console,GetRemark,CommonAttribute,Sex,WriteLine,public,标注 From: https://www.cnblogs.com/dzw159/p/16927404.html