2013-02-20 88 views
3

我在那里,我给一个对象,并需要将情况:转换对象集合

  • 确定该物体是一个单一的对象或一个集合(数组,列表等)
  • 如果是一个集合,尽管列表中的一步。

我到目前为止。测试IEnumerable不起作用。而转换为IEnumerable只适用于非原始类型。

static bool IsIEnum<T>(T x) 
{ 
    return null != typeof(T).GetInterface("IEnumerable`1"); 
} 
static void print(object o) 
{ 
    Console.WriteLine(IsIEnum(o));  // Always returns false 
    var o2 = (IEnumerable<object>)o;  // Exception on arrays of primitives 
    foreach(var i in o2) { 
     Console.WriteLine(i); 
    } 
} 
public void Test() 
{ 
    //int [] x = new int[]{1,2,3,4,5,6,7,8,9}; 
    string [] x = new string[]{"Now", "is", "the", "time..."}; 
    print(x);  
} 

任何人都知道如何做到这一点?

+3

如果你为什么地球上您使用的对象泛型?为什么不打印(T obj)?另外,你试过的是IEnumerable而不是GetInterface?并且为了运行时检查你不应该使用typeof,你应该使用GetType。 – 2013-02-20 16:22:40

+0

谢谢,所有。我用Snippet编译器测试并没有注意到它是“使用System.Collections.Generic;”默认。我曾尝试过非泛型IEnumerable,并且在更改为“使用System.Collections”之前出现错误。 – 2013-02-20 17:26:48

回答

6

这足以检查对象是转换到非通用IEnumerable接口:

var collection = o as IEnumerable; 
if (collection != null) 
{ 
    // It's enumerable... 
    foreach (var item in collection) 
    { 
     // Static type of item is System.Object. 
     // Runtime type of item can be anything. 
     Console.WriteLine(item); 
    } 
} 
else 
{ 
    // It's not enumerable... 
} 

IEnumerable<T>本身实现IEnumerable,因此这将为通用和非通用工种的一致好评。使用此接口而不是通用接口避免了通用接口差异的问题:IEnumerable<T>不一定可转换为IEnumerable<object>

这个问题讨论了通用接口方差在更多的细节:Generic Variance in C# 4.0

0

不要使用IEnumerable

static void print(object o) 
{ 
    Console.WriteLine(IsIEnum(o));  // Always returns false 
    var o2 = o as IEnumerable;  // Exception on arrays of primitives 
    if(o2 != null) { 
     foreach(var i in o2) { 
     Console.WriteLine(i); 
     } 
    } 
} 

通用版本,您将错过某些类型的,可以在foreach如果你使用这样做。可在foreach被用作收集的对象并不需要实现IEnumerable它只是需要实现GetEnumerator而这又需要返回具有Current属性和MoveNext方法

如果集合键入一个类型而你只需要支持不同类型的集合,你可以在这种情况下做

static void print<T>(T o) { 
    //Not a collection 
} 

static void print<T>(IEnumerable<T> o) { 
    foreach(var i in o2) { 
     Console.WriteLine(i); 
    } 
} 

方法重载会接你取决于对象是否是一个集合了正确的方法(在这种情况下,通过定义实施IEnumerable<T>

0

使用下面的代码:

Type t = typeof(System.Collections.IEnumerable); 

Console.WriteLine(t.IsAssignableFrom(T)); //returns true for collentions 
+0

字符串也实现'IEnumerable',所以你需要过滤字符串。 – Sam 2017-10-24 22:22:55