将数组转换为IEnumerable <T>

Dan*_*ous 71 c# arrays generics casting

假设您有一个基本Employee类:

class Employee
{
   public string Name;
   public int Years;
   public string Department;
}
Run Code Online (Sandbox Code Playgroud)

然后(在一个单独的类中)我有以下代码片段(我想我理解除了最后一个):

我相信下面的代码片段是有效的,因为数组initiliser创建了一个Employee对象数组,它们与分配给的workforce变量的类型相同.

Employee[] workforceOne = new Employee[] {
   new Employee() { Name = "David", Years = 0, Department = "software" },
   new Employee() { Name = "Dexter", Years = 3, Department = "software" },
   new Employee() { Name = "Paul", Years = 4, Department = "software" } };
Run Code Online (Sandbox Code Playgroud)

然后我有以下代码片段.我相信这是有效的,因为Employee对象数组的含义是实现的Array()类的实现IEnumerable.因此,我相信这就是为什么数组可以分配给IEnumerable?

IEnumerable workforceTwo = new Employee[] {
   new Employee() { Name = "David", Years = 0, Department = "software" },
   new Employee() { Name = "Dexter", Years = 3, Department = "software" },
   new Employee() { Name = "Paul", Years = 4, Department = "software" } };
Run Code Online (Sandbox Code Playgroud)

然后我有这个代码片段:

IEnumerable<Employee> workforceThree = new Employee[] {
   new Employee() { Name = "David", Years = 0, Department = "software" },
   new Employee() { Name = "Dexter", Years = 3, Department = "software" },
   new Employee() { Name = "Paul", Years = 4, Department = "software" } };
Run Code Online (Sandbox Code Playgroud)

我不确定为什么这段代码片段有效? IEnumerable<Employee>继承自IEnumerable(并覆盖(或重载?)GetEnumerator()方法)但是我不应该因此需要使用上面的转换来工作:

//The cast does work but is not required
IEnumerable<Employee> workforceFour = (IEnumerable<Employee>)new Employee[] {
   new Employee() { Name = "David", Years = 0, Department = "software" },
   new Employee() { Name = "Dexter", Years = 3, Department = "software" },
   new Employee() { Name = "Paul", Years = 4, Department = "software" } };
Run Code Online (Sandbox Code Playgroud)

似乎数组是从一种类型的隐式向下转换IEnumerable,IEnumerable<Employee>但我总是认为当你需要将类型转换为更具体的类型时,你需要一个显式的转换.

也许我在这里的理解中遗漏了一些简单的东西,但有人可以帮我理解这个.

谢谢.

Hei*_*nzi 101

文档:

在.NET Framework 2.0版,Array类实现System.Collections.Generic.IList<T>,System.Collections.Generic.ICollection<T>以及System.Collections.Generic.IEnumerable<T>通用接口.这些实现在运行时提供给数组,因此文档构建工具不可见.因此,通用接口不会出现在Array类的声明语法中,并且没有可通过将数组转换为通用接口类型(显式接口实现)来访问的接口成员的参考主题.

因此,你的Employee[]工具IEnumerable<Employee>.

  • 为了澄清,它不是实现它的Array类,它是任何T的T []. (6认同)

Den*_*aub 5

默认情况下,员工数组实现IEnumerable<Employee>以及IEnumerable