将数组转换为 IEnumerable

2024-03-28

假设你有基本的Employee类如下:

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

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

我相信以下代码片段有效,因为数组初始化程序创建了一个 Employee 对象数组,这些对象与分配给的劳动力变量的类型相同。

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" } };

然后我有以下代码片段。我相信这是有效的,因为数组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" } };

然后我有这个代码片段:

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" } };

我不确定这个代码片段为什么有效? 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" } };

看起来该数组是从一种类型隐式向下转换的IEnumerable to IEnumerable<Employee>但我一直认为,当您需要将类型转换为更具体的类型时,您需要显式强制转换。

也许我在这里缺少一些简单的理解,但有人可以帮助我理解这一点。

谢谢。


From 文档 http://msdn.microsoft.com/en-us/library/system.array.aspx:

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

因此,你的Employee[]实施IEnumerable<Employee>.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将数组转换为 IEnumerable 的相关文章

随机推荐