问题描述
我有一个System.Type
实例,我想执行以下操作:
- 检查类型是否继承自
IEnumerable<>
- 如果是,请获取其继承自
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 (将#修改为@)