Cast object to IEnumerable<object>?

后端 未结 2 1802
余生分开走
余生分开走 2021-02-20 08:33

How can I cast an object to IEnumerable?

I know that the object implements IEnumerable but I don\'t kn
2条回答
  •  名媛妹妹
    2021-02-20 09:16

    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 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 as an IEnumerable.
    2. This wouldn't work in C# 4 either despite the fact that IEnumerable is covariant, since variance is not supported for value-types - the cast from int[] (an IEnumerable) --> IEnumerable can't succeed.

      提交回复
      热议问题