如何判断对象是否为IEnumerable
代码:
namespace NS {
class Program {
static IEnumerable<int> GetInts() {
yield return 1;
}
static void Main() {
var i = GetInts();
var type = i.GetType();
Console.WriteLine(type.ToString());
}
}
}
输出:
NS.1.Program+<GetInts>d__0
如果我将 GetInts 更改为返回 IList,则一切正常 输出是:
System.Collections.Generic.List`1[System.Int32]
这会返回 false:
namespace NS {
class Program {
static IEnumerable<int> GetInts() {
yield return 1;
}
static void Main() {
var i = GetInts();
var type = i.GetType();
Console.WriteLine(type.Equals(typeof(IEnumerable<int>)));
}
}
}
最佳答案
如果您指的是集合,那么就是as
:
var asEnumerable = i as IEnumerable<int>;
if(asEnumerable != null) { ... }
但是,我假设(根据示例)您有一个 Type
:
对象 永远不会是“属于”类型 IEnumerable<int>
- 但它可能实现它;我希望:
if(typeof(IEnumerable<int>).IsAssignableFrom(type)) {...}
会做。如果您不知道 T
(上面的 int
),然后检查所有实现的接口(interface):
static Type GetEnumerableType(Type type) {
if (type.IsInterface && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return type.GetGenericArguments()[0];
foreach (Type intType in type.GetInterfaces()) {
if (intType.IsGenericType
&& intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
return intType.GetGenericArguments()[0];
}
}
return null;
}
并调用:
Type t = GetEnumerableType(type);
如果为空,则不是 IEnumerable<T>
对于任何 T
- 否则检查 t
.
关于c# - 确定集合是否属于 IEnumerable<T> 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1846671/