C# GetGenericTypeDefinition在查找IEnumerable时返回false<;T>;在列表中<;T>;
下面,为什么C# GetGenericTypeDefinition在查找IEnumerable时返回false<;T>;在列表中<;T>;,c#,reflection,list,ienumerable,C#,Reflection,List,Ienumerable,下面,为什么在这种情况下是可枚举的: Type type = typeof(List<string>); bool enumerable = (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)); Type Type=typeof(列表); bool enumerable=(type.IsGenericType&&type.GetGenericTy
在这种情况下是可枚举的
:
Type type = typeof(List<string>);
bool enumerable = (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>));
Type Type=typeof(列表);
bool enumerable=(type.IsGenericType&&type.GetGenericTypeDefinition()==typeof(IEnumerable));
返回false
编辑1 由于上述方法不起作用,确定类是否实现IEnumerable的最佳方法是什么 因为
(typeof(List<String>)).GetGenericTypeDefinition()
以下内容返回true,并切中要害地检查接口:
enumerable = typeof(List<string>).GetInterfaces()
.Contains(typeof(IEnumerable<string>));
enumerable=typeof(List).GetInterfaces()
.包含(typeof(IEnumerable));
在这里,我可以使用GetListType(type)
并检查null
:
static Type GetListType(Type type) {
foreach (Type intType in type.GetInterfaces()) {
if (intType.IsGenericType
&& intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
return intType.GetGenericArguments()[0];
}
}
return null;
}
静态类型GetListType(类型){
foreach(Type.GetInterfaces()中的intType类型){
如果(intType.IsGenericType
&&intType.GetGenericTypeDefinition()==typeof(IEnumerable)){
返回intType.GetGenericArguments()[0];
}
}
返回null;
}
如果您想要对特定的封闭泛型类型进行快速测试-例如,检查List
是否实现了IEnumerable
,那么您可以执行以下操作:
Type test = typeof(List<string>);
bool isEnumerable = typeof(IEnumerable<string>).IsAssignableFrom(test);
Type test=typeof(列表);
bool isEnumerable=类型(IEnumerable)。IsAssignableFrom(测试);
如果您想要一个适用于任何IEnumerable
的更通用的解决方案,那么您需要使用类似以下内容:
Type test = typeof(List<string>);
bool isEnumerable = test.GetInterfaces().Any(i =>
i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IEnumerable<>)));
Type test=typeof(列表);
bool isEnumerable=test.GetInterfaces().Any(i=>
i、 IsGenericType&(i.GetGenericTypeDefinition()==typeof(IEnumerable));
Nice one-Marc,这是唯一一个符合我要求并对我有效的示例。不幸的是,您的示例返回false。您是指我说仅使用assignable from
的示例“gives false”?
Type test = typeof(List<string>);
bool isEnumerable = typeof(IEnumerable<string>).IsAssignableFrom(test);
Type test = typeof(List<string>);
bool isEnumerable = test.GetInterfaces().Any(i =>
i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IEnumerable<>)));