如何确定物体的类型的IEnumerable&LT的; T>
code:
命名空间的NS {
类节目{
静态的IEnumerable< INT> GetInts(){
收益率的回报1;
}
静态无效的主要(){
VAR I = GetInts();
VAR类型= i.GetType();
Console.WriteLine(type.ToString());
}
}
}
输出:
NS.1.Program +< GetInts> d__0
如果我改变GetInts返回IList中,一切都OK 输出结果是:
System.Collections.Generic.List`1 [System.Int32的]
和这个返回false:
命名空间的NS {
类节目{
静态的IEnumerable< INT> GetInts(){
收益率的回报1;
}
静态无效的主要(){
VAR I = GetInts();
VAR类型= i.GetType();
Console.WriteLine(type.Equals(typeof运算(IEnumerable的< INT>)));
}
}
}
解决方案
如果你指的是集合,然后只需为
:
VAR asEnumerable =我为IEnumerable< INT取代;
如果(asEnumerable!= NULL){...}
不过,我(从例子)假设你有一个键入
:
在对象的永远不会是式的IEnumerable< INT>
- 但它可能的执行的它;我希望是:
如果(typeof运算(IEnumerable的< INT>)IsAssignableFrom(类型)){...}
会做。如果你不知道 T
( INT
在上面),然后检查所有实现的接口:
静态类型GetEnumerableType(类型类型){
的foreach(类型IntType上在type.GetInterfaces()){
如果(intType.IsGenericType
&功放;&安培; intType.GetGenericTypeDefinition()== typeof运算(IEnumerable的<>)){
返回intType.GetGenericArguments()[0];
}
}
返回null;
}
和调用:
键入T = GetEnumerableType(类型);
如果这是空,是不是的IEnumerable< T>
任何 T
- 否则检查 T
。
How to determine if object is of type IEnumerable <T>?
Code:
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());
}
}
}
Output:
NS.1.Program+<GetInts>d__0
If I change GetInts to return IList, everything is OK the output is:
System.Collections.Generic.List`1[System.Int32]
And this returns 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>)));
}
}
}
解决方案
If you mean the collection, then just as
:
var asEnumerable = i as IEnumerable<int>;
if(asEnumerable != null) { ... }
However, I'm assuming (from the example) that you have a Type
:
The object will never be "of" type IEnumerable<int>
- but it might implement it; I would expect that:
if(typeof(IEnumerable<int>).IsAssignableFrom(type)) {...}
would do. If you don't know the T
(int
in the above), then check all the implemented interfaces:
static Type GetEnumerableType(Type type) {
foreach (Type intType in type.GetInterfaces()) {
if (intType.IsGenericType
&& intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
return intType.GetGenericArguments()[0];
}
}
return null;
}
and call:
Type t = GetEnumerableType(type);
if this is null, it isn't IEnumerable<T>
for any T
- otherwise check t
.