简体   繁体   English

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

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

I was implementing my own ArrayList class and was left surprised when I realised that 我正在实现自己的ArrayList类,当我意识到这一点时,我感到很惊讶

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

didn't work. 没用。 What is the reason arrays don't implement IEnumerator in .NET? 数组在.NET中不实现IEnumerator的原因是什么?

Is there any work-around? 有没有解决方法?

Thanks 谢谢

Arrays do implement IEnumerable<T> , but it is done as part of the special knowledge the CLI has for arrays. 数组确实实现了IEnumerable<T> ,但它是作为CLI对数组的特殊知识的一部分完成的。 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. 许多工具都不会显示此实现,这在Array类概述的备注部分中有所描述。

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

You can use generic method IEnumerable<T> OfType<T>() from System.Linq namespace, which extends IEnumerable interface. 您可以使用System.Linq命名空间中的泛型方法IEnumerable<T> OfType<T>() ,它扩展了IEnumerable接口。 It will filter out all elements which type is different than T and return IEnumerable<T> collection . 它将过滤掉所有类型不同于T的元素并返回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 . 如果使用(IEnumerable<T>)_array转换运算符,则可能不安全,因为System.Array (和其他非泛型类型)存储System.Object类型的项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM