我想编写一个使用反射来判断给定类型是否实现了 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);
}
代码不起作用,它总是返回false。显然,像 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。当type是已实例化的IList<T>
,例如IList<int>
,IList<object>
等时,将返回true。但它对于实现IList<T>
的类(如List<int>
,ObservableCollection<double>
等)返回false,因此显然IList<>
不能从List<>
分配。这与我的预期不同。
我该如何编写IsGenericList并使其像上面的示例一样工作?
IList
替换了ICollection
,那么IsGenericList(typeof(IList<int>))
将返回False。请参考以下修复方法:https://dev59.com/W3NA5IYBdhLWcg3wdtpd#13589104 - Colonel Panic