我有这样一个情况,我被给予了一个对象,并需要做以下事情:
- 确定该对象是单个对象还是集合(Array、List等)
- 如果它是一个集合,则遍历该列表。
到目前为止,我所拥有的并不能测试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);
}
有人知道如何做到这一点吗?