将对象转换为集合

Joh*_*opp 3 c# runtime type-conversion

我有一个情况,我得到一个对象,需要:

  • 确定该对象是单个对象还是集合(数组,列表等)
  • 如果它是一个集合,请通过列表.

到目前为止我有什么.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);       
}
Run Code Online (Sandbox Code Playgroud)

有人知道怎么做吗?

Ric*_*ook 8

检查对象是否可以转换为非泛型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...
}
Run Code Online (Sandbox Code Playgroud)

IEnumerable<T>本身实现IEnumerable,所以这将适用于泛型和非泛型类型.使用此接口而不是通用接口可避免通用接口差异的问题:IEnumerable<T>不一定可转换为IEnumerable<object>.

这个问题更详细地讨论了通用接口方差:C#4.0中的通用方差