CLR如何在数组上实现IEnumerable <T>?

Tom*_*ter 6 c# arrays ienumerable

我意识到数组实现IEnumerable<T>"在运行时".根据数据的MSDN文档:

从.NET Framework 2.0开始,Array类实现System.Collections.Generic.IList<T>,System.Collections.Generic.ICollection<T>以及System.Collections.Generic.IEnumerable<T>通用接口.这些实现在运行时提供给数组,因此,泛型接口不会出现在Array类的声明语法中.

当然,这是正确的.在查看源代码时,Array您会看到它仅实现了非泛型版本IEnumerable.

如果运行下面的代码片段,您将看到泛型Enumerator的类型System.SZArrayHelper+SZGenericArrayEnumerator`1[System.String].

String[] array = new[] { "Apple", "Banana", "Grape" };
IEnumerator enumer = ((IEnumerable<String>)array).GetEnumerator();

// Next line writes: System.SZArrayHelper+SZGenericArrayEnumerator`1[System.String]
Console.WriteLine(enumer.GetType());
Run Code Online (Sandbox Code Playgroud)

我希望有人能够提供一些关于 CLR 如何IEnumerable<T>在运行时实现的见解?实现这一目标的机制是什么?在CLR中是硬编码的还是Array类中有什么东西可以通知CLR动态实现泛型版本?

作为后续工作,我正在阅读"Nutshell中的C#5,0"和第274页,作者声称Array该类必须实现非IEnumerable向后版本的"向后兼容性".有人可以举例说明这种"向后兼容性"的必要性吗?