纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
3.1 KiB

3 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.ComponentModel;
  8. namespace ICSSoft.Common
  9. {
  10. public static class EnumHelper
  11. {
  12. #region 获取枚举注解
  13. /// <summary>
  14. /// 判单枚举中是否包含该枚举描述
  15. /// </summary>
  16. /// <param name="enumType"></param>
  17. /// <param name="desc"></param>
  18. /// <returns></returns>
  19. public static bool HasDescriptions(Type enumType,string desc)
  20. {
  21. if (enumType != null && enumType.IsEnum)
  22. {
  23. FieldInfo[] fields = enumType.GetFields();
  24. for (int i = 1; i < fields.Length; ++i)
  25. {
  26. //object fieldValue = Enum.Parse(enumType, fields[i].Name);
  27. object[] attrs = fields[i].GetCustomAttributes(true);
  28. foreach (object attr in attrs)
  29. {
  30. if (typeof(DescriptionAttribute).IsAssignableFrom(attr.GetType()) && ((DescriptionAttribute)attr).Description.Equals(desc))
  31. {
  32. return true;
  33. }
  34. }
  35. }
  36. }
  37. return false;
  38. }
  39. #endregion
  40. public static string GetDescription<Attr>(this Enum em) where Attr : AttrDescription
  41. {
  42. Type enumType = em.GetType();
  43. var name = Enum.GetName(enumType, em);
  44. if (name == null)
  45. return string.Empty;
  46. object[] objs = enumType.GetField(name).GetCustomAttributes(typeof(Attr), false);
  47. if (objs == null || objs.Length == 0)
  48. return string.Empty;
  49. Attr attr = objs[0] as Attr;
  50. return attr.Description;
  51. }
  52. public static string GetDescription(this Enum em)
  53. {
  54. Type enumType = em.GetType();
  55. var name = Enum.GetName(enumType, em);
  56. if (name == null)
  57. return string.Empty;
  58. object[] objs = enumType.GetField(name).GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
  59. if (objs == null || objs.Length == 0)
  60. return string.Empty;
  61. System.ComponentModel.DescriptionAttribute attr = objs[0] as System.ComponentModel.DescriptionAttribute;
  62. return attr.Description;
  63. }
  64. }
  65. #region 用于枚举的特性类
  66. public class AttrDescription : Attribute
  67. {
  68. private string _showName;
  69. public AttrDescription(string desc)
  70. {
  71. _showName = desc;
  72. }
  73. public string Description
  74. {
  75. get
  76. {
  77. return _showName;
  78. }
  79. }
  80. }
  81. public class DBValue : AttrDescription
  82. {
  83. public DBValue(string desc)
  84. : base(desc)
  85. {
  86. }
  87. }
  88. //public class DescriptionEn : AttrDescription
  89. //{
  90. // public DescriptionEn(string desc)
  91. // : base(desc)
  92. // {
  93. // }
  94. //}
  95. #endregion
  96. }