Cast object to IEnumerable<object>?

放肆的年华 提交于 2020-01-01 08:34:13

问题


How can I cast an object to IEnumerable<object>?

I know that the object implements IEnumerable<object> but I don't know what type it is. It could be an array, a List<T>, or whatever.


A simple test case I'm trying to get working:

static void Main(string[] args)
{
    object arr = new[] { 1, 2, 3, 4, 5 };
    foreach (var item in arr as IEnumerable<object>)
        Console.WriteLine(item);
    Console.ReadLine();
}

回答1:


It's hard to answer this without a concrete use-case, but you may find it sufficient to simply cast to the non-generic IEnumerable interface.

There are two reasons why this will normally work for most types that are considered "sequences".

  1. The "classic" .NET 1.x collection classes implement IEnumerable.
  2. The generic IEnumerable<T> interface inherits from IEnumerable, so the cast should work fine for the generic collection classes in System.Collections.Generic, LINQ sequences etc.

EDIT:

As for why your provided sample doesn't work:

  1. This wouldn't work in C# 3 because it doesn't support generic interface covariance - you can't view an IEnumerable<Derived> as an IEnumerable<Base>.
  2. This wouldn't work in C# 4 either despite the fact that IEnumerable<T> is covariant, since variance is not supported for value-types - the cast from int[] (an IEnumerable<int>) --> IEnumerable<object> can't succeed.



回答2:


I ran into the same issue with covariance not supporting value types, I had an object with and actual type of List<Guid> and needed an IEnumerable<object>. A way to generate an IEnumerable when just IEnumerable isn't good enough is to use the linq Cast method

((IEnumerable)lhsValue).Cast<object>()


来源:https://stackoverflow.com/questions/4632313/cast-object-to-ienumerableobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!