Created
June 4, 2013 03:44
-
-
Save dfmartin/5703425 to your computer and use it in GitHub Desktop.
Comparing Type with GenericType to determine if a type is derived from a generic type where the generic argument type is unknown.
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
[TestClass] | |
public class UnitTest1 | |
{ | |
[TestMethod] | |
public void TestMethod1() | |
{ | |
Assert.IsTrue(typeof(Foo<>).IsAssignableFrom(typeof(Bar))); // fails | |
} | |
[TestMethod] | |
public void TestIsSubClassOfRaw() | |
{ | |
Assert.IsTrue(IsSubclassOfRawGeneric(typeof(Foo<>), typeof(Bar))); // passes | |
} | |
[TestMethod] | |
public void GetGenericTypeDef() | |
{ | |
Assert.AreEqual(typeof(Foo<>), typeof(Bar).BaseType.GetGenericTypeDefinition()); // passes | |
} | |
[TestMethod] | |
public void IsSubClassBasic() | |
{ | |
Assert.IsTrue(typeof(Bar).IsSubclassOf(typeof(Foo<>))); // fails | |
} | |
static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) | |
{ | |
//method borrowed from StackOverflow question http://stackoverflow.com/a/457708/117428 | |
while (toCheck != null && toCheck != typeof(object)) | |
{ | |
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; | |
if (generic == cur) | |
{ | |
return true; | |
} | |
toCheck = toCheck.BaseType; | |
} | |
return false; | |
} | |
} | |
internal class Bar : Foo<string> | |
{ | |
} | |
internal class Foo<T> | |
{ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment