假设你有一个基本的Employee
类这样:铸造阵列的IEnumerable <T>
class Employee
{
public string Name;
public int Years;
public string Department;
}
然后(在一个单独的类)我有下面的代码片段(我想我明白所有,但最后一个):
我相信下面的代码片段的工作原理是因为数组initiliser创建了一个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
IEnumerable<Employee>
继承(α和覆盖(或过载)的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
@Aliostad:它位于'workforceThree'片段的正下方。 – Heinzi
+1好问题! – Gishu