EnumExtensions.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Reflection;
  5. namespace Common
  6. {
  7. /// <summary>
  8. /// 枚举扩展方法
  9. /// </summary>
  10. public static class EnumExtension
  11. {
  12. /// <summary>
  13. /// 返回枚举项的描述信息。
  14. /// </summary>
  15. /// <param name="value">要获取描述信息的枚举项。</param>
  16. /// <returns>枚举想的描述信息。</returns>
  17. public static string GetEnumDescription(this Enum value)
  18. {
  19. Type enumType = value.GetType();
  20. // 获取枚举常数名称。
  21. string name = Enum.GetName(enumType, value);
  22. if (name != null)
  23. {
  24. // 获取枚举字段。
  25. FieldInfo fieldInfo = enumType.GetField(name);
  26. if (fieldInfo != null)
  27. {
  28. // 获取描述的属性。
  29. DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo,
  30. typeof(DescriptionAttribute), false) as DescriptionAttribute;
  31. if (attr != null)
  32. {
  33. return attr.Description;
  34. }
  35. }
  36. }
  37. return null;
  38. }
  39. /// <summary>
  40. /// 获取彩种对应数据库表名称
  41. /// </summary>
  42. /// <param name="value">彩种枚举类型</param>
  43. /// <returns></returns>
  44. public static string GetLotteryTableName(this Enum value)
  45. {
  46. if (value == null)
  47. {
  48. throw new ArgumentException("value");
  49. }
  50. string tableName = String.Empty;
  51. var fieldInfo = value.GetType().GetField(value.ToString());
  52. var attributes = (CustomAttribute.TableNameAttribute[])fieldInfo.GetCustomAttributes(typeof(CustomAttribute.TableNameAttribute), false);
  53. if (attributes.Length > 0)
  54. {
  55. tableName = attributes[0].TableName;
  56. }
  57. return tableName;
  58. }
  59. }
  60. }