1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace WCS.Utils
- {
- public class EnumHelper
- {
- public static string GetDescription(Enum value)
- {
- if (value == null)
- {
- throw new ArgumentException("value");
- }
- string description = value.ToString();
- var fieldInfo = value.GetType().GetField(description);
- var attributes =
- (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
- if (attributes != null && attributes.Length > 0)
- {
- description = attributes[0].Description;
- }
- return description;
- }
- public static string GetEnumDescription<T>(string enumName) where T : Enum
- {
- Type enumType = typeof(T);
- if (!enumType.IsEnum)
- {
- throw new ArgumentException("T must be an enumerated type");
- }
- var enumField = enumType.GetField(enumName);
- if (enumField == null)
- {
- throw new ArgumentException($"No enum found with name {enumName} in {enumType}");
- }
- var attributes = (EnumDescriptionAttribute[])enumField.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
- return attributes.Length > 0 ? attributes[0].Description : enumName;
- }
- }
- }
|