假设您有一个基本的Employee
类,如下所示:
class Employee
{
public string Name;
public int Years;
public string Department;
}
然后(在另一个类中),我有以下代码片段(我认为除了最后一个,都理解了):
我相信以下代码片段之所以有效,是因为数组初始化器创建了与分配给workforce变量相同类型的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
转换为 IEnumerable<Employee>
,但我一直认为当你需要将一个类型转换为更具体的类型时,需要显式转换。
也许我的理解中缺少了一些简单的东西,但有人能帮助我理解一下吗?
谢谢。