C#中的阵列改变维数 [英] C# Changing the number of dimensions in an array

查看:102
本文介绍了C#中的阵列改变维数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能,在C#,到一个多维阵列转换成一个一维阵列,而不必所有元素从一个拷贝到其他,是这样的:

Is it possible, in C#, to convert a multi-dimensional array into a 1D array without having to copy all the elements from one to the other, something like:

int[,] x = new int[3,4];
int[] y = (int[])x;

这将允许使用x的,就好像它是一个12元一维数组(以及从功能恢复等),但该编译器不允许这种转换。

This would allow the use of x as if it were a 12-element 1D array (and to return it from a function as such), but the compiler does not allow this conversion.

据我所知,一个二维数组(或更高维数)在连续的内存布局,因此它似乎没有不可能的,这可以在某种程度上工作。使用不安全固定可以允许通过一个指针访问,但是这并不返回数组一维帮助。

As far as I'm aware, a 2D array (or higher number of dimensions) is laid out in contiguous memory, so it doesn't seem impossible that it could work somehow. Using unsafe and fixed can allow access through a pointer, but this doesn't help with returning the array as 1D.

虽然我相信我可以只使用整个的情况下,我在present工作的一维数组,它将若该功能是介于两者之间的适配器,它返回一个多维数组和别的东西的一部分是有用的这需要一个1D之一。

While I believe I can just use a 1D array throughout in the case I'm working on at present, it would be useful if this function was part of an adapter between something which returns a multidimensional array and something else which requires a 1D one.

推荐答案

您不能,这不是在C#中可能阵列的这种方式进行转换。你也许可以通过使用一个外部DLL(C / C ++)做到这一点,但你必须保持你的阵列在一个固定的位置。

You can't, it's not possible in C# to convert array's this way. You maybe could do it by using a external dll ( C/C++ ), but then you need to keep your array at a fixed location.

一般来说,我会建议避免使用二维数组,因为theese在C#慢,最好使用锯齿状阵列或者甚至更好的单dimensionals与数学的一点点。

Generally i would advice to avoid using a 2D array because theese are slow in C#, better use jagged-array or even better single dimensionals with a little bit of math.

Int32[] myArray = new Int32[xSize * ySize];

// Access
myArray[x + (y * xSize)] = 5;

这篇关于C#中的阵列改变维数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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