gpt4 book ai didi

.net - 如何判断 Type 是否实现了 IList<>?

转载 作者:行者123 更新时间:2023-12-03 02:12:55 25 4
gpt4 key购买 nike

我想编写一个方法,使用反射来判断给定类型是否实现 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。当类型被实例化时,这将返回 true IList<T>IList<int> , IList<object>等等。但对于实现 IList<T> 的类,它返回 false如List<int> , ObservableCollection<double>等等,显然IList<>不可从 List<> 分配。再说一次,这不是我所期望的。

我该如何编写 IsGenericList 并使其像上面的示例一样工作?

最佳答案

事实上,您不能拥有泛型类型定义的实例。因此,IsAssignableFrom() 方法按预期工作。要实现您想要的目标,请执行以下操作:

public bool IsGenericList(Type type)
{
if (type == null) {
throw new ArgumentNullException("type");
}
foreach (Type @interface in type.GetInterfaces()) {
if (@interface.IsGenericType) {
if (@interface.GetGenericTypeDefinition() == typeof(ICollection<>)) {
// if needed, you can also return the type used as generic argument
return true;
}
}
}
return false;
}

出于好奇,你需要这个做什么?

关于.net - 如何判断 Type 是否实现了 IList<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/951536/

25 4 0