从System.Type实例获取基本类型的通用参数

问题描述

我有一个System.Type实例,我想执行以下操作:

  1. 检查类型是否继承自IEnumerable<>
  2. 如果是,请获取其继承自IEnumerable<>类型的通用参数的类型

我不能简单地使用以下代码:

public Type GetGenericEnumerableArgumentType(Type type)
{
    if (typeof(IEnumerable<>).IsAssignableFrom(type))
    {
        // This would be incorrect - see below
        return type.GetGenericArguments().First();
    }

    return null;
}

如果通过以下任何一种方式定义输入类型,则以上代码将无法正常工作:

public class MyCustomEnumerable : IEnumerable<double>
{
    ...
}

public class AnotherCustomEnumerable<T,U> : IEnumerable<U>
{
    ...
}

在第一种情况下,我想要获得typeof(double),在第二种情况下,我想要获得typeof(U)。有没有简单的方法可以做到这一点?一种选择是递归检查type.BaseType,但我想必须对此问题有一个更简单的解决方案。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...