gpt4 book ai didi

c# - 将数组转换为 IEnumerable

转载 作者:IT王子 更新时间:2023-10-29 03:41:37 25 4
gpt4 key购买 nike

假设您有一个基本的 Employee这样的类:

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

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

我相信下面的代码片段是有效的,因为数组初始化器创建了一个 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" } };

然后我有以下代码片段。我相信这是可行的,因为 Employee 的数组objects implicity 是 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 类型隐式向下转换的至 IEnumerable<Employee>但我一直认为,当您需要将类型转换为更具体的内容时,您需要进行显式转换。

也许我在这里的理解中遗漏了一些简单的东西,但是有人可以帮助我理解这件事吗。

谢谢。

最佳答案

来自 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).

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

关于c# - 将数组转换为 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7173266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com