且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 C# 多维数组不实现 IEnumerable<T>?

更新时间:2022-01-10 15:56:32

CLR 有两种不同类型的数组:vectors,它们保证是一维的,下限为 0,以及可以具有非零边界和非 0 秩的更通用数组.

The CLR has two different kinds of arrays: vectors which are guaranteed to be one-dimensional with a lower bound of 0, and more general arrays which can have non-zero bounds and a rank other than 0.

来自 CLI 规范的第 8.9.1 节:

From section 8.9.1 of the CLI spec:

此外,一个创建的向量元素类型 T,实现界面System.Collections.Generic.IList(第 8.7 节),其中 U := T.

Additionally, a created vector with element type T, implements the interface System.Collections.Generic.IList<U> (§8.7), where U := T.

我不得不说这对我来说似乎很奇怪.鉴于它已经实现了 IEnumerable,我不明白为什么它不应该实现 IEnumerable.实现 IList 没有多大意义,但简单的通用接口就可以了.

I have to say it seems pretty weird to me. Given that it already implements IEnumerable I don't see why it shouldn't implement IEnumerable<T>. It wouldn't make as much sense to implement IList<T>, but the simple generic interface would be fine.

如果你想要这个,你可以调用 Cast(如果你使用 .NET 3.5)或者编写你自己的方法来遍历数组.为了避免强制转换,您必须编写自己的方法来找到每个维度的下限/上限,并以这种方式获取内容.不是很愉快.

If you want this, you could either call Cast<T> (if you're using .NET 3.5) or write your own method to iterate through the array. To avoid casting you'd have to write your own method which found the lower/upper bounds of each dimension, and fetched things that way. Not terribly pleasant.