Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.