From 6ee1135732e56641877d3f5b21b5870553301051 Mon Sep 17 00:00:00 2001 From: Michael Becker Date: Sun, 21 Jul 2024 22:38:38 -0400 Subject: [PATCH] add TypeExtensions to support Type.IsSubclassOfGeneric(...) --- .../lib/MBS.Core/Reflection/TypeExtensions.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 framework-dotnet/src/lib/MBS.Core/Reflection/TypeExtensions.cs diff --git a/framework-dotnet/src/lib/MBS.Core/Reflection/TypeExtensions.cs b/framework-dotnet/src/lib/MBS.Core/Reflection/TypeExtensions.cs new file mode 100644 index 0000000..b7930ed --- /dev/null +++ b/framework-dotnet/src/lib/MBS.Core/Reflection/TypeExtensions.cs @@ -0,0 +1,32 @@ +namespace MBS.Core.Reflection; + +public static class TypeExtensions +{ + public static bool IsSubclassOfGeneric(this Type toCheck, Type generic) + { + // thanks https://stackoverflow.com/a/457708 + + while (toCheck != null && toCheck != typeof(object)) + { + var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; + if (generic == cur) + { + return true; + } + + Type[] intfs = toCheck.GetInterfaces(); + foreach (Type intf in intfs) + { + // !!! HACK HACK HACK !!! + bool hack = intf.Namespace.Equals(generic.Namespace) && intf.Name.Equals(generic.Name); + if (hack) + { + return true; + } + } + toCheck = toCheck.BaseType; + } + return false; + } + +} \ No newline at end of file