| 123456789101112131415161718192021222324252627282930313233343536373839 |
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace StandardLibrary
- {
- public static class EnumExt
- {
- public static bool TryParseEnum<T>(object value, out T result) where T : struct, Enum
- {
- result = default;
- if (Enum.IsDefined(typeof(T), value))
- {
- result = (T)Enum.ToObject(typeof(T), value);
- return true;
- }
- return false;
- }
- /// <summary>
- /// 获取枚举值的 Description 特性文本,如果没有则返回枚举名称
- /// </summary>
- public static string GetDescription(this Enum value)
- {
- var field = value.GetType().GetField(value.ToString());
- if (field == null) return value.ToString();
- var attribute = Attribute.GetCustomAttribute(
- field,
- typeof(DescriptionAttribute)) as DescriptionAttribute;
- return attribute?.Description ?? value.ToString();
- }
- }
- }
|