【发布时间】:2011-08-24 09:35:12
【问题描述】:
假设您有一个基本的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 对象数组是实现 IEnumerable 的 Array() 类的实现。因此,我相信这就是为什么可以将数组分配给 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> 但我一直认为,当您需要将类型转换为更具体的类型时,您需要显式转换。
也许我在这里的理解中遗漏了一些简单的东西,但有人可以帮助我理解这一点。
谢谢。
【问题讨论】:
-
@Aliostad:它就在
workforceThree片段的下方。
标签: c# arrays generics casting