c# - 如何检测 T 是否为 IEnumerable<T2>,如果是则获取 T2 的类型?

标签 c# generics reflection

我知道 this问题,跟进,还有this一个,但我无法以一种可以帮助我做我想做的事情的方式将它们放在一起:

我有一个通用类型,我想检查 T 是一个 struct或者如果它实现了 IEnumerable<T2> ,然后我想检查 T2 是 struct .

到目前为止,我已经到了这里('请原谅这些乱七八糟的代码,这是实验性的):

private class TestClass<T>
{
    public TestClass()
    {
        Type type = typeof(T);
        //(detecting T == IEnumerable<something> ommitted for clarity)
        Type enumerableType = type.GetInterfaces()
                .Where(t => t.IsGenericType)
                .Select(t => t.GetGenericTypeDefinition())
                .Where(t => t == typeof(IEnumerable<>))
                .FirstOrDefault();
        if(enumerableType != null) 
        {
            Type enumeratedType = type.GetGenericArguments().First();
            if(!enumeratedType.IsValueType) //throw etc...
        }
    }
}

我遇到的问题是 enumerableTypeIEnumerable<> , 所以 enumeratedType结果为 T ,而不是我传入的任何内容(例如 new TestClass<int[]>() )。

最佳答案

您的问题是您已经选择了具有所有数据的类型,以支持它被删除的通用类型模板。

尝试:

    Type enumerableType = type.GetInterfaces()
            .Where(t => t.IsGenericType)
            .Where(t => t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            .Select(t => t.GetGenericArguments()[0])
            .FirstOrDefault();

关于c# - 如何检测 T 是否为 IEnumerable<T2>,如果是则获取 T2 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4626016/

相关文章:

c# - 使用 Html helper HiddenFor C# MVC 将模型添加到模型中

c# - "Two-way binding requires Path or XPath"编辑 wpf 数据网格时

java - 为什么泛型在 Java 中的数组中被删除?

c# - 奇怪的通用行为

java - 反射类仅初始化一次

c# - 是否可以根据其他复选框状态来选中/取消选中某个复选框?

c# - 嵌套的 json 对象不使用 Json.NET 更新/继承

c# - 我可以在单个泛型类型上指定多个约束吗?

java - 使用 entityClass.newInstance() 创建的实例上的 invokeExact 导致 java.lang.invoke.WrongMethodTypeException?

c# - 使用反射发现派生类型