zs
2025-04-30 3933f3629ec6282e5f070923f04bbf2c1add6687
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using KissUtil.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
 
namespace CMS.Plugin.HIAWms.Domain.Shared.Util
{
    /// <summary>
    /// 枚举帮助类.
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举.
        /// </summary>
        /// <param name="enumName"> </param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static List<EnumItem> GetEnumItems(string enumName)
        {
            // 获取当前程序集中的所有类型
            var enumType = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes())
                .FirstOrDefault(t => t.Name == enumName && t.IsEnum);
 
            if (enumType == null)
            {
                throw new UserFriendlyException($"枚举类型 {enumName} 不存在");
            }
 
            return GetEnumItems(enumType);
        }
 
        /// <summary>
        /// 获取枚举类型.
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static List<EnumItem> GetEnumItems(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new UserFriendlyException("提供的类型不是枚举类型");
            }
 
            var result = new List<EnumItem>();
            var values = Enum.GetValues(enumType);
 
            foreach (var value in values)
            {
                var fieldInfo = enumType.GetField(value.ToString());
                var description = fieldInfo?
                    .GetCustomAttributes(typeof(DescriptionAttribute), false)
                    .FirstOrDefault() as DescriptionAttribute;
 
                result.Add(new EnumItem
                {
                    Value = (int)value,
                    Name = value.ToString(),
                    Description = description?.Description ?? value.ToString(),
                });
            }
 
            return result;
        }
    }
 
    /// <summary>
    /// 枚举描述.
    /// </summary>
    public class EnumItem
    {
        public int Value { get; set; }
 
        public string Name { get; set; }
 
        public string Description { get; set; }
    }
}