Created
November 6, 2012 19:21
-
-
Save cammerman/4026865 to your computer and use it in GitHub Desktop.
Type extensions to help check for generic closure.
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 TypeExtensions | |
{ | |
public static bool Closes(this Type type, Type checkType) | |
{ | |
if (!checkType.IsGenericTypeDefinition) | |
throw new ArgumentException("Type being checked against is not an open generic type."); | |
return | |
type.IsGenericType | |
&& type.GetGenericTypeDefinition() == checkType; | |
} | |
public static IEnumerable<Type> InheritanceChain(this Type type) | |
{ | |
yield return type; | |
var currentType = type.BaseType; | |
while (currentType != null) | |
{ | |
yield return currentType; | |
currentType = currentType.BaseType; | |
} | |
} | |
public static bool Implements<T>(this Type type) | |
{ | |
return type.Implements(typeof(T)); | |
} | |
public static bool Implements(this Type type, Type check) | |
{ | |
if (check.IsGenericTypeDefinition) | |
return | |
type.Closes(check) | |
|| type.InheritanceChain().Any(@class => @class.Closes(check)) | |
|| type.GetInterfaces().Any(@interface => @interface.Closes(check)); | |
return check.IsAssignableFrom(type); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment