【发布时间】:2016-10-06 14:39:02
【问题描述】:
我正在尝试实现 OfType 的替代方案,您将所需的类型指定为 Type 实例参数,而不是使用类型参数化,但我不确定实现它的“正确方法”是什么。这是我目前所拥有的:
public static IEnumerable<T> OfType<T>(this IEnumerable<T> enumerable, Type type)
{
return enumerable.Where(element => type.IsInstanceOfType(element));
}
我最初是从下面的代码开始的,但意识到它不支持继承......
public static IEnumerable<T> OfType<T>(this IEnumerable<T> enumerable, Type type)
{
return enumerable.Where(element => element.GetType() == type);
}
然后我考虑了几秒钟比较基本类型,然后才想到这可能是个坏主意。
所以我的问题是,在提供的类型相同的情况下,顶部的代码是否总是返回与 OfType 相同的结果?换句话说,下面代码示例中的集合parametrizedFiltered 和typeInstanceFiltered 是否会包含相同的元素,或者我会走多远?
IEnumerable<InterfaceType> someCollection = BlackBox.GetCollection();
IEnumerable<DerivedType> parametrizedFiltered = someCollection.OfType<DerivedType>();
IEnumerable<InterfaceType> typeInstanceFiltered = someCollection.OfType(typeof(DerivedType));
【问题讨论】:
-
您可以查看
IsAssignableFrom进行“深度”继承检查。 -
@JeroenvanLangen 我认为
IsAssignableFrom(x.GetType())等效于IsInstanceOfType(x),当您忽略null情况时。不过,缓存IsAssignableFrom的结果可能会提高性能。 -
数组协方差和可空值类型的行为相同。接口协方差也应该起作用。
-
所以你基本上是在问
obj is TResult是否与typeof(TResult).IsInstanceOfType(obj)相同 -
主要区别在于
OfType返回您指定的类型的IEnumerable,因为您正在执行的操作将返回原始类型的IEnumerable“匹配”已过滤。
标签: c# linq generics reflection types