From 03e852fd2e668d5f27b78f427c8864669b651c25 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Fri, 9 Feb 2018 09:38:16 -0500 Subject: [PATCH] Caching class attributes --- ICD.Common.Utils/AttributeUtils.cs | 36 +++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/ICD.Common.Utils/AttributeUtils.cs b/ICD.Common.Utils/AttributeUtils.cs index 6db55a3..e9cf173 100644 --- a/ICD.Common.Utils/AttributeUtils.cs +++ b/ICD.Common.Utils/AttributeUtils.cs @@ -25,6 +25,7 @@ namespace ICD.Common.Utils private static readonly IcdHashSet s_CachedTypes; private static readonly Dictionary s_AttributeToMethodCache; + private static readonly Dictionary s_AttributeToTypeCache; private static readonly Dictionary> s_TypeToAttributesCache; private static ILoggerService Logger { get { return ServiceProvider.TryGetService(); } } @@ -38,6 +39,7 @@ namespace ICD.Common.Utils s_CachedTypes = new IcdHashSet(); s_AttributeToMethodCache = new Dictionary(); + s_AttributeToTypeCache = new Dictionary(); s_TypeToAttributesCache = new Dictionary>(); } @@ -129,14 +131,11 @@ namespace ICD.Common.Utils try { -#if SIMPLSHARP s_TypeToAttributesCache[type] = new IcdHashSet(type.GetCustomAttributes(false)); + foreach (Attribute attribute in s_TypeToAttributesCache[type]) + s_AttributeToTypeCache[attribute] = type; + methods = type.GetMethods(); -#else - s_TypeToAttributesCache[type] = - new IcdHashSet(ReflectionExtensions.GetCustomAttributes(type.GetTypeInfo(), false)); - methods = type.GetTypeInfo().GetMethods(); -#endif } // GetMethods for Open Generic Types is not supported. catch (NotSupportedException) @@ -170,6 +169,18 @@ namespace ICD.Common.Utils #region Lookup + /// + /// Gets the class attributes of the given generic type. + /// + /// + /// + public static IEnumerable GetClassAttributes() + where T : Attribute + { + return s_AttributeToTypeCache.Select(kvp => kvp.Key) + .OfType(); + } + /// /// Gets the first attribute on the given class type matching the generic type. /// @@ -218,6 +229,19 @@ namespace ICD.Common.Utils : Enumerable.Empty(); } + /// + /// Gets the type with the given attribute. + /// + /// + /// + public static Type GetClass(Attribute attribute) + { + if (attribute == null) + throw new ArgumentNullException("attribute"); + + return s_AttributeToTypeCache[attribute]; + } + /// /// Gets all of the cached method attributes of the given type. ///