C# 中任意等级数组的索引
我需要迭代任意排名的数组。这适用于读取和写入,因此 GetEnumerator
将不起作用。
Array.SetValue(object, int)
不适用于多维数组。 Array.SetValue(object, params int[]) 需要过多的算术来迭代多维空间。它还需要动态调用来绕过签名的 params 部分。
我很想固定数组并用指针迭代它,但我找不到任何说明多维数组保证是连续的文档。如果它们在尺寸的末尾有填充,那么这是行不通的。我也希望避免不安全的代码。
有没有一种简单的方法可以仅使用单个索引来顺序寻址多维数组?
I need to iterate over an array of arbitrary rank. This is for both reading and writing, so GetEnumerator
will not work.
Array.SetValue(object, int)
doesn't work on multidimensional arrays.Array.SetValue(object, params int[])
would require excessive arithmetic for iterating through the multidimensional space. It would also require dynamic invocation to get around the params
part of the signature.
I'm tempted to pin the array and iterate over it with a pointer, but I can't find any documentation that says that multidimensional arrays are guaranteed to be contiguous. If they have padding at the end of a dimension then that won't work. I'd also prefer to avoid unsafe code.
Is there an easy way to sequentially address a multidimensional array using only a single index?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
多维数组保证是连续的。来自 ECMA-335:
所以这有效:
Multidimensional arrays are guaranteed to be contiguous. From ECMA-335:
So this works:
您可以使用
Rank
和GetUpperBound
属性/方法创建索引数组,并将其传递给数组的SetValue
和GetValue< /code> 方法:
..并像这样使用它:
You can use the
Rank
andGetUpperBound
property/method to create an indices array that you can pass to the array'sSetValue
andGetValue
methods:..and use it like so:
也许您可以将它们全部加入到一个临时集合中,然后对其进行迭代。
Perhaps you could join them all into the a single temporary collection, and just iterate over that.