我知道 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...
}
}
}
我遇到的问题是 enumerableType
是IEnumerable<>
, 所以 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/