为什么在.NET数组只能实现IEnumerable而不是IEnumerable的< T>?数组、而不是、NET、IEnumerable

2023-09-02 10:55:30 作者:冷拥

我正在实施自己的ArrayList类,并留下惊讶,当我意识到

I was implementing my own ArrayList class and was left surprised when I realised that

public System.Collections.Generic.IEnumerator<T> GetEnumerator() {
    return _array.GetEnumerator();
}

没有工作。什么是数组不要在.NET中实现IEnumerator的原因是什么?

didn't work. What is the reason arrays don't implement IEnumerator in .NET?

有没有什么解决方法?

感谢

推荐答案

阵列都实施的IEnumerable&LT; T&GT; ,但它是作为的专业知识的CLI部分有数组。许多工具将不再显示此实现。看到言论段开始注意到在文档(文档早期.NET版本:外观为重要块)

Arrays do implement IEnumerable<T>, but it is done as part of the special knowledge the CLI has for arrays. Many tools will not show this implementation. See the paragraph in the remarks starting "Starting with the .NET Framework 2.0" note in the documentation (documentation for earlier .NET versions: look for the "Important" block).

您可以添加一个转换:

return ((IEnumerable<T>)_array).GetEnumerator();