最佳答案
假设您有这样一个基本的 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 ()类的实现。因此,我相信这就是为什么数组可以被分配给 IEnumable?
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>
类型,但我一直认为,当需要将类型转换为更具体的类型时,需要显式转换。
也许我错过了一些简单的东西,在我的理解这里,但有人可以帮助我了解这一点。
谢谢你。