zoukankan      html  css  js  c++  java
  • 【点滴积累】通过特性(Attribute)为枚举添加更多的信息

      特性(Attribute)是将额外数据关联到一个属性(以及其他构造)的一种方式,而枚举则是在编程中最常用的一种构造,枚举本质上其实是一些常量值,相对于直接使用这些常量值,枚举为我们提供了更好的可读性。我们知道枚举的基础类型只能是值类型(bytesbyteshortushortintuintlong 或 ulong),一般的情况下枚举能够满足我们的需求,但是有时候我们需要为枚举附加更多信息,仅仅只是使用这些值类型是不够的,这时通过对枚举类型应用特性可以使枚举带有更多的信息。

    在枚举中使用DescriptionAttribute特性

      首先引入:using System.ComponentModel 命名空间,下面是一个枚举应用了DescriptionAttribute特性:

    1     enum Fruit
    2     {
    3         [Description("苹果")]
    4         Apple,
    5         [Description("橙子")]
    6         Orange,
    7         [Description("西瓜")]
    8         Watermelon
    9     }

    下面是一个获取Description特性的扩展方法:

     1         /// <summary>
     2         /// 获取枚举描述特性值
     3         /// </summary>
     4         /// <typeparam name="TEnum"></typeparam>
     5         /// <param name="enumerationValue">枚举值</param>
     6         /// <returns>枚举值的描述/returns>
     7         public static string GetDescription<TEnum>(this TEnum enumerationValue)
     8             where TEnum : struct, IComparable, IFormattable, IConvertible
     9         {
    10             Type type = enumerationValue.GetType();
    11             if (!type.IsEnum)
    12             {
    13                 throw new ArgumentException("EnumerationValue必须是一个枚举值", "enumerationValue");
    14             }
    15 
    16             //使用反射获取该枚举的成员信息
    17             MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
    18             if (memberInfo != null && memberInfo.Length > 0)
    19             {
    20                 object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
    21 
    22                 if (attrs != null && attrs.Length > 0)
    23                 {
    24                     //返回枚举值得描述信息
    25                     return ((DescriptionAttribute)attrs[0]).Description;
    26                 }
    27             }
    28             //如果没有描述特性的值,返回该枚举值得字符串形式
    29             return enumerationValue.ToString();
    30         }

    最后,我们就可以利用该扩展方法获取该枚举值得描述信息了:

    1     public static void Main(string[] args)
    2     {
    3         //description = "橙子"
    4         string description = Fruit.Orange.GetDescription();
    5     }
  • 相关阅读:
    Java异常处理和设计
    一次qps测试实践
    Alternate Task UVA
    Just Another Problem UVA
    Lattice Point or Not UVA
    Play with Floor and Ceil UVA
    Exploring Pyramids UVALive
    Cheerleaders UVA
    Triangle Counting UVA
    Square Numbers UVA
  • 原文地址:https://www.cnblogs.com/IPrograming/p/Enum_DescriptionAttribute.html
Copyright © 2011-2022 走看看