可以对数组进行不依赖于数组秩的操作。迭代器也不总是合适的解决方案。给定数组
double[,] myarray = new double[10,5];
实现以下工作流程是可取的:
- 将 Rank>1 的数组 reshape 为 rank=1 且元素数量相同的线性数组。这应该发生在适当的位置以提高运行时效率。不允许复制。
- 将 reshape 后的数组传递给仅为 Rank=1 数组定义的方法。例如数组.copy()
- 将结果数组 reshape 为原始排名和维度。
关于这个主题有一个类似的问题:How to reshape array in c# .那里的解决方案使用 BlockCopy() 的内存复制操作。
我的问题是: 这种reshaping不用内存拷贝能实现吗?或者甚至以一种临时的方式,比如创建数据的新 View ?
最佳答案
这方面的措辞有点艰难,但肯定指针 unsafe
和 fixed
会起作用。无内存拷贝,直接访问,加胡椒和盐调味
CLR 不会让您随心所欲地转换数组,您能想到的任何其他方法都需要分配一个新数组并进行复制(请注意,您可以快速闪电)。唯一可能的其他方法是使用 fixed,这将为您提供连续的一维数组。
unsafe public static void SomeMethod(int* p, int size)
{
for (var i = 0; i < 4; i++)
{
//Perform any linear operation
*(p + i) *= 10;
}
}
...
var someArray = new int[2,2];
someArray[0, 0] = 1;
someArray[0,1] = 2;
someArray[1, 0] = 3;
someArray[1, 1] = 4;
//Reshape an array to a linear array
fixed (int* p = someArray)
{
SomeMethod(p, 4);
}
//Reshape result array to original rank and dimensions.
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine(someArray[i, j]);
}
}
输出
10
20
30
40
关于c# - 就地 reshape c# 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51401300/