【发布时间】:2009-06-04 16:12:09
【问题描述】:
我想编写一个使用反射来判断给定类型是否实现IList<T> 的方法。例如:
IsGenericList(typeof(int)) // should return false
IsGenericList(typeof(ArrayList)) // should return false
IsGenericList(typeof(IList<int>)) // should return true
IsGenericList(typeof(List<int>)) // should return true
IsGenericList(typeof(ObservableCollection<int>)) // should return true
在我的使用中,我可以假设该类型将始终是实例化的泛型类型(或根本不是泛型的东西)。
不幸的是,这并不像应该的那么容易。显而易见的解决方案:
public bool IsGenericList(Type type)
{
return typeof(IList<>).IsAssignableFrom(type);
}
不起作用;它总是返回假。显然,像 IList<> 这样的非实例化泛型类型并没有像我期望的那样实现 IsAssignableFrom:IList<> 不能从 List<T> 分配。
我也试过这个:
public bool IsGenericList(Type type)
{
if (!type.IsGenericType)
return false;
var genericTypeDefinition = type.GetGenericTypeDefinition();
return typeof(List<>).IsAssignableFrom(genericTypeDefinition);
}
即,将 type 转换为其非实例化泛型,例如 IList<int> -> IList<>,然后再次尝试 IsAssignableFrom。当类型是实例化的IList<T>(例如IList<int>、IList<object> 等)时,这将返回true。但是对于实现IList<T> 的类(例如List<int>、ObservableCollection<double> 等),它返回false,所以显然IList<> 不能从 List<> 分配。再次,不是我所期望的。
如何编写 IsGenericList 并使其像上面的示例一样工作?
【问题讨论】:
标签: .net generics reflection