Extension method for getting the immediate interfaces on a Type

This commit is contained in:
Chris Cameron
2018-03-28 11:24:03 -04:00
parent fb6ee9d468
commit 1ac5e26992
2 changed files with 47 additions and 0 deletions

View File

@@ -1,4 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ICD.Common.Utils.Extensions;
using NUnit.Framework;
@@ -93,6 +95,20 @@ namespace ICD.Common.Utils.Tests.Extensions
Assert.IsTrue(baseTypes.Contains(typeof(object)));
}
[Test]
public void GetImmediateInterfacesTest()
{
Type[] interfaces = typeof(ICollection<int>).GetImmediateInterfaces().ToArray();
Assert.AreEqual(1, interfaces.Length);
Assert.AreEqual(typeof(IEnumerable<int>), interfaces[0]);
interfaces = typeof(IEnumerable<int>).GetImmediateInterfaces().ToArray();
Assert.AreEqual(1, interfaces.Length);
Assert.AreEqual(typeof(IEnumerable), interfaces[0]);
}
private interface C
{
}

View File

@@ -47,6 +47,7 @@ namespace ICD.Common.Utils.Extensions
private static readonly Dictionary<Type, Type[]> s_TypeAllTypes;
private static readonly Dictionary<Type, Type[]> s_TypeBaseTypes;
private static readonly Dictionary<Type, Type[]> s_TypeImmediateInterfaces;
private static readonly Dictionary<Type, Type[]> s_TypeMinimalInterfaces;
/// <summary>
@@ -56,6 +57,7 @@ namespace ICD.Common.Utils.Extensions
{
s_TypeAllTypes = new Dictionary<Type, Type[]>();
s_TypeBaseTypes = new Dictionary<Type, Type[]>();
s_TypeImmediateInterfaces = new Dictionary<Type, Type[]>();
s_TypeMinimalInterfaces = new Dictionary<Type, Type[]>();
}
@@ -184,6 +186,35 @@ namespace ICD.Common.Utils.Extensions
} while (type != null);
}
/// <summary>
/// Gets the interfaces that the given type implements that are not implemented further
/// down the inheritance chain.
/// </summary>
/// <param name="extends"></param>
/// <returns></returns>
public static IEnumerable<Type> GetImmediateInterfaces(this Type extends)
{
if (extends == null)
throw new ArgumentNullException("extends");
if (!s_TypeImmediateInterfaces.ContainsKey(extends))
{
IEnumerable<Type> allInterfaces = extends.GetInterfaces();
IEnumerable<Type> childInterfaces =
extends.GetAllTypes()
.Except(extends)
.SelectMany(t => t.GetImmediateInterfaces())
.Distinct();
Type[] immediateInterfaces = allInterfaces.Except(childInterfaces).ToArray();
s_TypeImmediateInterfaces.Add(extends, immediateInterfaces);
}
return s_TypeImmediateInterfaces[extends];
}
/// <summary>
/// Gets the smallest set of interfaces for the given type that cover all implemented interfaces.
/// </summary>