Why do arrays in .net only implement IEnumerable and not IEnumerable<T>?

廉价感情. 提交于 2019-11-26 19:48:34

问题


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();
}

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

Is there any work-around?

Thanks


回答1:


Arrays do implement IEnumerable<T>, but it is done as part of the special knowledge the CLI has for arrays. This works as if it were an explicit implementation (but isn't: it is done at runtime). Many tools will not show this implementation, this is described in the Remarks section of the Array class overview.

You could add a cast:

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

Note, older MSDN (pre docs.microsoft.com) coverage of this changed a few times with different .NET versions, check for the remarks section.




回答2:


You can use generic method IEnumerable<T> OfType<T>() from System.Linq namespace, which extends IEnumerable interface. It will filter out all elements which type is different than T and return IEnumerable<T> collection. If you use (IEnumerable<T>)_array conversion operator, it might not be safe, because System.Array (and other nongeneric types) stores items of type System.Object.



来源:https://stackoverflow.com/questions/2773740/why-do-arrays-in-net-only-implement-ienumerable-and-not-ienumerablet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!