如何将对象转换为 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 接口。
有两个原因为什么这通常适用于被认为是序列的大多数类型。
至于为什么你提供的示例不工作:
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(); }解决方案
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".
EDIT:
As for why your provided sample doesn't work:
更多推荐
将对象强制转换为IEnumerable< object> ;?
发布评论