From fb6ee9d4681e7efea2ec4159b82c28a96fd9a16c Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Wed, 28 Mar 2018 09:58:32 -0400 Subject: [PATCH] Extension method for finding the minimal interfaces that a given type implements --- ICD.Common.Utils/Extensions/TypeExtensions.cs | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/ICD.Common.Utils/Extensions/TypeExtensions.cs b/ICD.Common.Utils/Extensions/TypeExtensions.cs index 8d2a20b..08b0571 100644 --- a/ICD.Common.Utils/Extensions/TypeExtensions.cs +++ b/ICD.Common.Utils/Extensions/TypeExtensions.cs @@ -46,7 +46,8 @@ namespace ICD.Common.Utils.Extensions }; private static readonly Dictionary s_TypeAllTypes; - private static readonly Dictionary s_TypeBaseTypes; + private static readonly Dictionary s_TypeBaseTypes; + private static readonly Dictionary s_TypeMinimalInterfaces; /// /// Static constructor. @@ -55,6 +56,7 @@ namespace ICD.Common.Utils.Extensions { s_TypeAllTypes = new Dictionary(); s_TypeBaseTypes = new Dictionary(); + s_TypeMinimalInterfaces = new Dictionary(); } /// @@ -181,5 +183,28 @@ namespace ICD.Common.Utils.Extensions yield return type; } while (type != null); } + + /// + /// Gets the smallest set of interfaces for the given type that cover all implemented interfaces. + /// + /// + /// + public static IEnumerable GetMinimalInterfaces(this Type extends) + { + if (extends == null) + throw new ArgumentNullException("extends"); + + if (!s_TypeMinimalInterfaces.ContainsKey(extends)) + { + Type[] allInterfaces = extends.GetInterfaces(); + Type[] minimalInterfaces = + allInterfaces.Except(allInterfaces.SelectMany(t => t.GetInterfaces())) + .ToArray(); + + s_TypeMinimalInterfaces.Add(extends, minimalInterfaces); + } + + return s_TypeMinimalInterfaces[extends]; + } } }