在 C# 中索引到任意等级的数组

Indexing into arrays of arbitrary rank in C#(在 C# 中索引到任意等级的数组)
本文介绍了在 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# 中索引到任意等级的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)