Przeglądaj źródła

Added GetCustomAttribute for enums

Kenric Nugteren 2 tygodni temu
rodzic
commit
4a9db9f391
1 zmienionych plików z 15 dodań i 2 usunięć
  1. 15 2
      InABox.Core/CoreUtils.cs

+ 15 - 2
InABox.Core/CoreUtils.cs

@@ -254,6 +254,15 @@ namespace InABox.Core
 
         public static bool HasAttribute<T>(this Type type) where T : Attribute => type.GetCustomAttribute<T>() != null;
 
+        public static T? GetCustomAttribute<T>(this Enum enumValue)
+            where T : Attribute
+        {
+            var enumType = enumValue.GetType();
+            var name = Enum.GetName(enumType, enumValue);
+            return enumType.GetField(name).GetCustomAttributes(false).OfType<T>().FirstOrDefault();
+        }
+
+
         public class GenericTypeBuilder
         {
             public Type Type { get; private set; }
@@ -1637,8 +1646,12 @@ namespace InABox.Core
         }
         //static readonly Regex StripQuotes = new Regex(@"&quot;", RegexOptions.Compiled);
 
-        
-        
+        public static string GetCaption(this Enum enumValue, bool usedefault = true)
+        {
+            var attribute = enumValue.GetCustomAttribute<Caption>();
+            return attribute?.Text
+                ?? (usedefault ? enumValue.ToString() : "");
+        }
 
         public static string GetCaption(this Type type, bool usedefault = true)
         {