mardi 24 février 2015

What is the equivalent of the "is" operator for reflected generic types?

Using the is operator in C# with generic types is straightforward:



if (new List<MyClass>()) is IEnumerable<MyClass>) {
// always branches
}


But what about when comparing types? I was hopeful that I could use Type.IsSubclassOf(Type type) here, but System.Collections.Generic.List<> implements System.Collections.Generic.IEnumerable<> -- It doesn't extend it. So I assume that's why the following happens:



var listType = typeof(List<MyClass>);
var enumerableType = typeof(IEnumerable<MyClass>);

if (listType.IsSubclassOf(enumerableType)) {
// NEVER branches
}


If I had an instance of my rvalue Type I could easily use Type.IsInstanceOfType(object o), but this point in the code is far removed from the instance from which the Type in question was reflected.


Am I missing something in the Type API? Am I forced to roll my own via an extension method?






Aucun commentaire:

Enregistrer un commentaire