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

后端 未结 2 633
星月不相逢
星月不相逢 2020-12-05 04:03

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

public System.Collections.Generic.IEnumerator GetEnumerator()          


        
2条回答
  •  旧时难觅i
    2020-12-05 04:53

    Arrays do implement IEnumerable, 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)_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.

提交回复
热议问题