Created
March 22, 2016 21:50
-
-
Save manisero/5a8dc338d35b565322a1 to your computer and use it in GitHub Desktop.
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 Type GetGenericTypeDefinitionImplementation(this Type type, Type definition) | |
{ | |
if (definition.IsInterface) | |
{ | |
return type.GetGenericInterfaceDefinitionImplementation(definition); | |
} | |
else | |
{ | |
return type.GetGenericClassDefinitionImplementation(definition); | |
} | |
} | |
public static Type GetGenericInterfaceDefinitionImplementation(this Type type, Type interfaceDefinition) | |
{ | |
if (type.IsInterface && type.ImplementsGenericDefinition(interfaceDefinition)) | |
{ | |
return type; | |
} | |
var interfaces = type.GetInterfaces(); | |
foreach (var @interface in interfaces) | |
{ | |
if (@interface.ImplementsGenericDefinition(interfaceDefinition)) | |
{ | |
return @interface; | |
} | |
} | |
return null; | |
} | |
public static Type GetGenericClassDefinitionImplementation(this Type type, Type classDefinition) | |
{ | |
if (type == typeof(object)) | |
{ | |
return null; | |
} | |
if (type.ImplementsGenericDefinition(classDefinition)) | |
{ | |
return type; | |
} | |
return type.BaseType.GetGenericClassDefinitionImplementation(classDefinition); | |
} | |
public static bool ImplementsGenericDefinition(this Type type, Type definition) | |
{ | |
return type.IsConstructedGenericType && type.GetGenericTypeDefinition() == definition; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment