Created
August 25, 2023 05:01
-
-
Save AldeRoberge/691875da494a23ca58c44d3310b4437d to your computer and use it in GitHub Desktop.
C# ReflectionUtils to get InheritsOrImplements certain class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ReflectionUtils | |
{ | |
public static bool InheritsOrImplements(this Type child, Type parent) | |
{ | |
parent = ResolveGenericTypeDefinition(parent); | |
var currentChild = child.IsGenericType | |
? child.GetGenericTypeDefinition() | |
: child; | |
while (currentChild != typeof(object)) | |
{ | |
if (parent == currentChild || HasAnyInterfaces(parent, currentChild)) | |
return true; | |
currentChild = currentChild.BaseType != null | |
&& currentChild.BaseType.IsGenericType | |
? currentChild.BaseType.GetGenericTypeDefinition() | |
: currentChild.BaseType; | |
if (currentChild == null) | |
return false; | |
} | |
return false; | |
} | |
private static bool HasAnyInterfaces(Type parent, Type child) | |
{ | |
return child.GetInterfaces() | |
.Any(childInterface => | |
{ | |
var currentInterface = childInterface.IsGenericType | |
? childInterface.GetGenericTypeDefinition() | |
: childInterface; | |
return currentInterface == parent; | |
}); | |
} | |
private static Type ResolveGenericTypeDefinition(Type parent) | |
{ | |
bool shouldUseGenericType = !(parent.IsGenericType && parent.GetGenericTypeDefinition() != parent); | |
if (parent.IsGenericType && shouldUseGenericType) | |
parent = parent.GetGenericTypeDefinition(); | |
return parent; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment