在 C# 中索引到任意等级的数组 [英] Indexing into arrays of arbitrary rank in C#

查看:28
本文介绍了在 C# 中索引到任意等级的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历任意等级的数组.这是用于读写的,所以 GetEnumerator 将不起作用.

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) 不适用于多维数组.Array.SetValue(object, params int[]) 将需要过多的算术来遍历多维空间.它还需要动态调用来绕过签名的 params 部分.

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?

推荐答案

保证多维数组是连续的.来自 ECMA-335:

Multidimensional arrays are guaranteed to be contiguous. From ECMA-335:

数组元素应在数组对象中按行优先顺序排列(即与最右边数组维度相关的元素应连续从最低到最高索引排列).

Array elements shall be laid out within the array object in row-major order (i.e., the elements associated with the rightmost array dimension shall be laid out contiguously from lowest to highest index).

所以这行得通:

int[,,,] array = new int[10, 10, 10, 10];

fixed (int* ptr = array)
{
    ptr[10] = 42;
}

int result = array[0, 0, 1, 0];  // == 42

这篇关于在 C# 中索引到任意等级的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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