Casting array to IEnumerable

后端 未结 3 1353
傲寒
傲寒 2020-12-02 21:53

Assume you have a basic Employee class as such:

class Employee
{
   public string Name;
   public int Years;
   public string Department;
}


        
相关标签:
3条回答
  • 2020-12-02 22:33

    From the documentation:

    In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations).

    Thus, your Employee[] implements IEnumerable<Employee>.

    0 讨论(0)
  • 2020-12-02 22:35

    Explicit cast is needed when some sentence needs to be downcasted. That's casting an object to a more specialized type - if the object is of such specialized type -.

    In the other hand, upcasting (casting to a less specialized type), will never need an explicit cast, but you can explicitly do it (it's just useless).

    Since Array implements IEnumerable and IEnumerable<T>, you're doing an upcast in your code, meaning _you don't need to explicitly cast to IEnumerable<T>.

    0 讨论(0)
  • 2020-12-02 22:38

    The Array of Employees by default implements IEnumerable<Employee> as well as IEnumerable

    0 讨论(0)
提交回复
热议问题