将对象强制转换为IEnumerable< object&gt ;?

编程入门 行业动态 更新时间:2024-10-28 12:21:36
本文介绍了将对象强制转换为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 接口。

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

  • 经典.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 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".

  • The "classic" .NET 1.x collection classes implement IEnumerable.
  • 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:

  • 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>.
  • 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 ;?

    本文发布于:2023-11-07 07:00:48,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1565833.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:转换为   对象   IEnumerable   amp   object

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!