为什么.net 中的数组只实现 IEnumerable 而不是 IEnumerable<T>? [英] Why do arrays in .net only implement IEnumerable and not IEnumerable&lt;T&gt;?

查看:30
本文介绍了为什么.net 中的数组只实现 IEnumerable 而不是 IEnumerable<T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现自己的 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,但它是作为 CLI 对数组的特殊知识的一部分完成的.这就像一个显式实现一样工作(但不是:它是在运行时完成的).许多工具不会显示此实现,这在 Array 类概述的noreferrer">备注部分.

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.

您可以添加演员表:

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

注意,旧的 MSDN(pre docs.microsoft.com)覆盖范围随着不同的 .NET 版本而改变了几次,请检查 备注 部分.

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

这篇关于为什么.net 中的数组只实现 IEnumerable 而不是 IEnumerable<T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆