假设您有一个Employee
这样的基本类:
class Employee
{
public string Name;
public int Years;
public string Department;
}
然后(在一个单独的类中)我有以下代码片段(我想我理解除了最后一个以外的所有内容):
我相信以下代码片段可以工作,因为数组初始化器创建了一个Employee对象数组,该对象与分配给其的forceforce变量具有相同的类型。
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
,IEnumerable<Employee>
但是我一直认为,当您需要将类型转换为更具体的类型时,需要显式转换。
也许我在这里缺少我所了解的一些简单信息,但是有人可以帮助我进行一些了解。
谢谢。
workforceThree
片段下面。