假设你有基本的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>
但我一直认为,当您需要将类型转换为更具体的类型时,您需要显式强制转换。
也许我在这里缺少一些简单的理解,但有人可以帮助我理解这一点。
谢谢。