索引到在C#中的任意级别的阵列 [英] Indexing into arrays of arbitrary rank in 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(对象,INT)
不多维数组。 Array.SetValue(对象,则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.
我很想针阵列并遍历它的指针,但我找不到,指出多维数组保证是连续的任何文件。如果他们在一个维度到底有填充那么将无法工作。我也preFER避免不安全code。
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屋!