为什么.net中的数组只实现IEnumerable而不是IEnumerable <T>?

dev*_*ium 42 .net c# arrays ienumerable ienumerator

我正在实现自己的ArrayList类,当我意识到这一点时,我感到很惊讶

public System.Collections.Generic.IEnumerator<T> GetEnumerator() {
    return _array.GetEnumerator();
}
Run Code Online (Sandbox Code Playgroud)

没用.数组在.NET中不实现IEnumerator的原因是什么?

有没有解决方法?

谢谢

Ric*_*ard 62

数组确实可以实现IEnumerable<T>,但它是作为CLI对数组的特殊知识的一部分完成的.这就好像它是一个显式实现(但不是:它在运行时完成).许多工具不会显示此实现,这在类概述的" 备注"部分中进行了Array描述.

你可以添加一个演员:

return ((IEnumerable<T>)_array).GetEnumerator();
Run Code Online (Sandbox Code Playgroud)

注意,较旧的MSDN(pre docs.microsoft.com)对此的覆盖范围在不同的.NET版本中有所改变,请检查备注部分.