| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 | using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Reflection;using System.Resources;using System.Text;using System.Threading.Tasks;/// <summary>/// 枚举扩展/// </summary>public static class EnumExtension{    /// <summary>    /// 获取枚举描述    /// </summary>    /// <param name="enumType">枚举类型</param>    /// <returns></returns>    public static string GetEnumDisplayName(this Enum enumType)    {        try        {            Type type = enumType.GetType();            var field = type.GetField(Enum.GetName(type, enumType));            var attr = field.GetCustomAttribute<DisplayAttribute>();            if (attr == null || string.IsNullOrWhiteSpace(attr.Name))                return enumType.ToString();            else                return attr.Name;        }        catch        {            return string.Empty;        }    }    public static T GetEnumByDisplayName<T>(this string displayName) where T : struct    {        Type type = typeof(T);        string[] names = Enum.GetNames(type);        string[] array = names;        foreach (string text in array)        {            DisplayAttribute customAttribute = type.GetField(text).GetCustomAttribute<DisplayAttribute>();            T result;            if (customAttribute == null)            {                if (text == displayName && Enum.TryParse(text, out result))                {                    return result;                }                continue;            }            string a;            if (customAttribute.ResourceType == null && string.IsNullOrEmpty(customAttribute.Name))            {                a = text;            }            else if (!(customAttribute.ResourceType != null))            {                a = (string.IsNullOrEmpty(customAttribute.Name) ? text : customAttribute.Name);            }            else            {                ResourceManager resourceManager = new ResourceManager(customAttribute.ResourceType);                a = resourceManager.GetString(customAttribute.Name);            }            if (a == displayName && System.Enum.TryParse(text, out result))            {                return result;            }        }        return (T)System.Enum.Parse(type, "0");    }   }
 |