将对象强制转换为IEnumerable< object&gt ;? [英] Cast object to IEnumerable<object>?

查看:164
本文介绍了将对象强制转换为IEnumerable< object&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象转换为 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 接口。



有两个原因为什么这通常适用于被认为是序列的大多数类型。


  1. 经典.NET 1.x集合类实现 IEnumerable

  2. 通用 IEnumerable< T> 接口从 IEnumerable 继承,所以cast应该适用于System.Collections.Generic中的通用集合类,



    至于为什么你提供的示例不工作:


    1. 这不会在C#3,因为它不支持通用接口协方差 - 您不能将 IEnumerable< Derived> 视为 IEnumerable< Base>

    2. 即使 IEnumerable< T> 是协变的,因为值类型不支持方差,这在C#从 int [] IEnumerable< int> IEnumerable< object> 无法成功。


    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".

    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.

    这篇关于将对象强制转换为IEnumerable&lt; object&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆