在C#中如何实现枚举类型的特性扩展和反射获取

来源:互联网 发布:sql给表增加字段 编辑:程序博客网 时间:2024/06/05 20:47

public enum 月定制项目
  {
            [CustomItemAttribute()]
            一点五元夜餐次数=1,
            [CustomItemAttribute()]
            二元夜餐次数=2,
            [CustomItemAttribute()]
             连班次数 =3,
            [CustomItemAttribute()]
            甲类保健津贴次数 =4,
            [CustomItemAttribute()]
            乙类保健津贴次数 =5,
            [CustomItemAttribute()]
            周六加班次数 =6,
            [CustomItemAttribute()]
            周日加班次数 =7,
            [CustomItemAttribute()]
            零点夜班次数 =8,
            [CustomItemAttribute()]
            节假日加班次数 =9,
            [CustomItemAttribute()]
            四点夜班次数 =10,
            [CustomItemAttribute()]
            事假天数=11,
            [CustomItemAttribute()]
            病假天数 =12,
            [CustomItemAttribute()]
            旷工天数 =13,
            [CustomItemAttribute()]
            公差天数 =14,
            [CustomItemAttribute()]
            探亲天数 =15,
            [CustomItemAttribute(CustomApplyType.工区员工)]
            效益工资 = 16
  } 
  public enum CustomApplyType
  {
            工区员工 = 1,
            机关员工 = 2,
            所有员工 = 3
  }
  [AttributeUsage(AttributeTargets.Field)]
  public class CustomItemAttribute:System.Attribute
  {
            protected CustomApplyType _customApplyType;
            public CustomItemAttribute(CustomApplyType customApplyType)
            {
                        this._customApplyType = customApplyType;
            }
            public CustomItemAttribute():this(CustomApplyType.所有员工)
            {
            }
            public CustomApplyType CustomApplyType{get{return this._customApplyType;}}
  } 
  class Application
  {
            [STAThread]
            static void Main(string[] args)
            {
                        FieldInfo[] fs = typeof(月定制项目).GetFields();
                        object enumInstance = typeof(月定制项目).Assembly.CreateInstance(typeof(月定制项目).FullName);
                        foreach(FieldInfo f in fs)
                        {
                                                CustomItemAttribute[] cas = (CustomItemAttribute[])f.GetCustomAttributes(typeof(CustomItemAttribute),true);
                                                if(cas.Length >0)
                                                {     
                                                            Console.WriteLine(f.GetValue(enumInstance));
                                                            Console.WriteLine(Convert.ToSingle((int)f.GetValue(enumInstance)));
                                                            Console.WriteLine(cas[0].CustomApplyType.ToString());
                                                }
                         }
                        Console.Read(); 

             }   
  }