| | 1 | | using System.ComponentModel; |
| | 2 | | using System.Reflection; |
| | 3 | |
|
| | 4 | | namespace MRA.Infrastructure.Enums; |
| | 5 | |
|
| | 6 | | public static class EnumExtensions |
| | 7 | | { |
| | 8 | | public static string GetDescription<TEnum>(this TEnum enumValue) where TEnum : Enum |
| | 9 | | { |
| 5 | 10 | | FieldInfo field = enumValue.GetType().GetField(enumValue.ToString()); |
| 5 | 11 | | if (field != null) |
| | 12 | | { |
| 5 | 13 | | DescriptionAttribute attribute = field.GetCustomAttribute<DescriptionAttribute>(); |
| 5 | 14 | | return attribute?.Description ?? enumValue.ToString(); |
| | 15 | | } |
| | 16 | |
|
| 0 | 17 | | return enumValue.ToString(); |
| | 18 | | } |
| | 19 | |
|
| | 20 | | public static TEnum GetDefaultValue<TEnum>() where TEnum : Enum |
| | 21 | | { |
| | 22 | | // Buscar el atributo DefaultEnumValue |
| 438 | 23 | | var attribute = typeof(TEnum) |
| 438 | 24 | | .GetCustomAttributes(typeof(DefaultEnumValueAttribute), false) |
| 438 | 25 | | .FirstOrDefault() as DefaultEnumValueAttribute; |
| | 26 | |
|
| 438 | 27 | | return attribute != null |
| 438 | 28 | | ? (TEnum)attribute.DefaultValue |
| 438 | 29 | | : default(TEnum); // Si no hay atributo, usar default |
| | 30 | | } |
| | 31 | | public static TEnum ToEnum<TEnum>(this int value) where TEnum : struct, Enum |
| | 32 | | { |
| 17 | 33 | | if (Enum.IsDefined(typeof(TEnum), value)) |
| | 34 | | { |
| 17 | 35 | | return (TEnum)Enum.ToObject(typeof(TEnum), value); |
| | 36 | | } |
| 0 | 37 | | throw new ArgumentException($"Value '{value}' is not defined for enum type '{typeof(TEnum).Name}'."); |
| | 38 | | } |
| | 39 | | } |