将对象强制转换为IEnumerable< object> ;? [英] Cast object to IEnumerable<object>?
问题描述
如何将对象
转换为 IEnumerable< object>
?
我知道对象实现 IEnumerable< object>
但我不知道它是什么类型。它可以是数组, List
或任何。
一个简单的测试用例我试图工作:
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();
}
一个具体的用例,但你可以发现它足以简单地转换到非通用的 IEnumerable
接口。
有两个原因为什么这通常适用于被认为是序列的大多数类型。
- 经典.NET 1.x集合类实现
IEnumerable
。 - 通用
IEnumerable< T>
接口从IEnumerable
继承,所以cast应该适用于System.Collections.Generic中的通用集合类, :
至于为什么你提供的示例不工作:
- 这不会在C#3,因为它不支持通用接口协方差 - 您不能将
IEnumerable< Derived>
视为IEnumerable< Base>
。 - 即使
IEnumerable< T>
是协变的,因为值类型不支持方差,这在C#从int []
(IEnumerable< int>
)IEnumerable< object>
无法成功。
How can I cast an
object
toIEnumerable<object>
?I know that the object implements
IEnumerable<object>
but I don't know what type it is. It could be an array, aList<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(); }
解决方案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".
- The "classic" .NET 1.x collection classes implement
IEnumerable
. - The generic
IEnumerable<T>
interface inherits fromIEnumerable
, 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:
- This wouldn't work in C# 3 because it doesn't support generic interface covariance - you can't view an
IEnumerable<Derived>
as anIEnumerable<Base>
. - 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 fromint[]
(anIEnumerable<int>
) -->IEnumerable<object>
can't succeed.
这篇关于将对象强制转换为IEnumerable< object> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 这不会在C#3,因为它不支持通用接口协方差 - 您不能将