I'm trying to implement an alternative to OfType where you specify the desired type as a Type instance argument instead of using type parametrization but I'm not sure what the 'correct way' to implement it is. This is what I have so far:
public static IEnumerable<T> OfType<T>(this IEnumerable<T> enumerable, Type type)
{
return enumerable.Where(element => type.IsInstanceOfType(element));
}
I initially started out with the code below, but realized it would not support inheritance...
public static IEnumerable<T> OfType<T>(this IEnumerable<T> enumerable, Type type)
{
return enumerable.Where(element => element.GetType() == type);
}
Then I thought about comparing base-types for few seconds before thinking that would probably be a bad idea.
So my question is will the code at the top always return the same result as OfType given the types provided are the same? In other words will the collections parametrizedFiltered
and typeInstanceFiltered
in the code example below contain the same elements or am I way off?
IEnumerable<InterfaceType> someCollection = BlackBox.GetCollection();
IEnumerable<DerivedType> parametrizedFiltered = someCollection.OfType<DerivedType>();
IEnumerable<InterfaceType> typeInstanceFiltered = someCollection.OfType(typeof(DerivedType));
Aucun commentaire:
Enregistrer un commentaire