将数组转换为IEnumerable <t> </t>

时间:2011-08-24 09:35:13

标签: c# arrays generics casting

假设你有一个基本的Employee课程:

class Employee
{
   public string Name;
   public int Years;
   public string Department;
}

然后(在一个单独的类中)我有以下代码片段(我想我理解除了最后一个):

我相信下面的代码片段是有效的,因为数组initiliser创建了一个Employee对象数组,它们与分配给的workforce变量的类型相同。

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<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>,但我一直认为当你需要将类型转换为更具体的类型时,你需要一个显式的转换。< / p>

也许我在这里的理解中遗漏了一些简单的东西,但有人可以帮助我理解这个。

谢谢。

3 个答案:

答案 0 :(得分:99)

来自the documentation

  

在.NET Framework 2.0版中,Array类实现System.Collections.Generic.IList<T>System.Collections.Generic.ICollection<T>System.Collections.Generic.IEnumerable<T>通用接口。这些实现在运行时提供给数组,因此文档构建工具不可见。因此,通用接口不会出现在Array类的声明语法中,并且没有可通过将数组转换为通用接口类型(显式接口实现)来访问的接口成员的参考主题。

因此,您的Employee[]实施IEnumerable<Employee>

答案 1 :(得分:4)

默认情况下,员工数组实现IEnumerable<Employee>以及IEnumerable

答案 2 :(得分:3)

当某个句子需要降级时,需要显式强制转换。那是将对象转换为更专业的类型 - 如果对象是这种特殊类型 - 。

另一方面,向上转换(转换为不太专业的类型),永远不需要显式转换,但你可以明确地执行它(它只是没用)。

由于Array实现了IEnumerableIEnumerable<T>,您在代码中执行 upcast ,这意味着_您不需要显式转换为IEnumerable<T>