为什么 C# 多维数组不实现 IEnumerable<T>? [英] Why do C# multidimensional arrays not implement IEnumerable<T>?

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

问题描述

我刚刚注意到 C# 中的多维数组没有实现 IEnumerable,但它实现了 IEnumerable.对于一维数组,IEnumerableIEnumerable 都实现了.

I have just noticed that a multidimensional array in C# does not implement IEnumerable<T>, while it does implement IEnumerable. For single-dimensional arrays, both IEnumerable<T> and IEnumerable are implemented.

为什么会有这种差异?如果一个多维数组是IEnumerable,它肯定也应该实现通用版本吗?我注意到这一点是因为我试图在多维数组上使用扩展方法,除非您使用 Cast 或类似方法,否则该方法会失败;所以我绝对可以看到使多维数组实现IEnumerable的参数.

Why this difference? If a multi-dimensional array is IEnumerable, surely it should also implement the generic version? I noticed this because I tried to use an extension method on a multidimensional array, which fails unless you use Cast<T> or similar; so I can definitely see the an argument for making multidimensional arrays implement IEnumerable<T>.

为了在代码中澄清我的问题,我希望下面的代码打印 true 四次,而它实际上打印 true, false, true, true:

To clarify my question in code, I would expect the following code to print true four times, while it actually prints true, false, true, true:

int[] singleDimensionArray = new int[10];
int[,] multiDimensional = new int[10, 10];

Debug.WriteLine(singleDimensionArray is IEnumerable<int>);
Debug.WriteLine(multiDimensional is IEnumerable<int>);
Debug.WriteLine(singleDimensionArray is IEnumerable);
Debug.WriteLine(multiDimensional is IEnumerable);

推荐答案

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.

这篇关于为什么 C# 多维数组不实现 IEnumerable&lt;T&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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