在List <T>中查找IEnumerable <T>时,GetGenericTypeDefinition返回false

Rya*_*all 4 c# reflection ienumerable list

关注这个问题,为什么会enumerable这样:

Type type = typeof(List<string>);
bool enumerable = (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>));
Run Code Online (Sandbox Code Playgroud)

回来false


编辑1

由于上述方法不起作用,确定类是否实现IEnumerable的最佳方法是什么?

Mar*_*ell 8

在这里,我可能会使用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;
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*ard 5

因为

(typeof(List<String>)).GetGenericTypeDefinition()
Run Code Online (Sandbox Code Playgroud)

回来了

typeof(List<>)
Run Code Online (Sandbox Code Playgroud)

GetGenericTypeDefinition 只能返回一种类型,不能返回目标实例实现的所有未绑定类型 Type

确定是否X<T>实施IY<T>任一

  • Reify T(即使其成为真实类型),并检查具体类型。即X<string>执行IY<string>. 这可以通过反射或与as操作员一起完成。

  • Type.GetInterafces()(或Type.GetInterface(t))。

第二个会更容易。特别是因为这也给出了错误:

Type t = typeof(List<string>).GetGenericTypeDefinition();
bool isAssign = typeof(IEnumerable<>).IsAssignableFrom(t);
Run Code Online (Sandbox Code Playgroud)