jt
2021-06-10 5d0d028456874576560552f5a5c4e8b801786f11
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace HH.WMS.Entitys.Enums
{
    public static class EnumExtensions
    {
        /// <summary>
        /// 获取特性 (DescriptionAttribute) 的说明;如果未使用该特性,则返回枚举的名称。
        /// </summary>
        /// <param name="enumValue"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum enumValue)
        {
            FieldInfo fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
            DescriptionAttribute[] attrs =
                fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
 
            return attrs.Length > 0 ? attrs[0].Description : enumValue.ToString();
        }
 
        public static string GetName(this Enum enumValue)
        {
            return enumValue.ToString();
        }
 
        public static T GetEnumByName<T>(string name)
        {
            try
            {
                name = name.Trim();
                var enumValue = (T)Enum.Parse(typeof(T), name);
                return enumValue;
            }catch(Exception){
                return (T)Enum.Parse(typeof(T), "ERROR"); ;
            }
            
        }
    }
}