zoukankan      html  css  js  c++  java
  • 获取指定类型如枚举/属性上自定义attribue值

    有时候我们用数字来区分一些类型,如1:中国银行,2:建设银行,3:工商银行,……。
    这时候我在代码中通常会定义枚举来与定义的一一对应,并在该枚举值上设置特性来表示所代表的含义,这样避免多处写一些数字来标识所代表的类型。而且后续添加修改也很方便。


    首先,自定义一个特性描述类:
     1     public class DescriptionAttribute : Attribute
     2     {
     3         public static readonly DescriptionAttribute Default;
     4 
     5         public DescriptionAttribute();
     6         public DescriptionAttribute(string description);
     7 
     8         public virtual string Description { get; }
     9         protected string DescriptionValue { get; set; }
    10 
    11         public override bool Equals(object obj);
    12         public override int GetHashCode();
    13     }

    定义枚举:
    1 public enum EnumType
    2 3   [Description("第一")]
    4   FIRST,
    5   [Description("第二")]
    6   SECOND,
    7   [Description("第三")]
    8   THIRD,
    9

    将枚举特性值转为注释信息:
     1         /// <summary>
     2         /// 将枚举特性值转为注释信息
     3         /// </summary>
     4         /// <param name="enumType"></param>
     5         /// <returns></returns>
     6         public static string ToString<T>(this T enumType)
     7         {
     8             Type type = enumType.GetType();
     9             FieldInfo fd = type.GetField(enumType.ToString());
    10             if (fd == null)
    11                 return string.Empty;
    12             var attributes = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
    13 
    14             var txt = string.Empty;
    15             foreach (DescriptionAttribute attr in attributes)
    16             {
    17                 txt = attr.Description;
    18                 break;
    19             }
    20             return txt;
    21         }

    调用:

    1 var name = EnumType.FIRST.ToString<EnumType>();
    2 //第一

  • 相关阅读:
    P1067 多项式输出(模拟水题)
    A. The Fair Nut and Elevator(暴力)
    A. The Fair Nut and Elevator(暴力)
    Knight Tournament (set)
    jquery怎么添加多个类名
    jquery对类的操作,添加,删除,点击添加,再点击删除
    jquery操作css样式的方法
    jquery浅复制和深复制区别
    TS 三种函数的定义方式
    ES7及ES8新特性
  • 原文地址:https://www.cnblogs.com/shouwu/p/6710633.html
Copyright © 2011-2022 走看看