C#更改数组中的维数

时间:2012-03-12 08:52:07

标签: c# arrays

在C#中,是否有可能将多维数组转换为一维数组,而无需将所有元素从一个复制到另一个,如:

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

这将允许使用x,就好像它是一个12元素的1D数组(并从函数中返回它),但编译器不允许这种转换。

据我所知,2D阵列(或更多维度)在连续的内存中布局,因此它似乎不可能以某种方式工作。使用unsafefixed可以允许通过指针进行访问,但这对于将数组作为1D返回没有帮助。

虽然我相信我可以在我目前正在处理的情况下使用一维数组,但是如果这个函数是返回多维数组的东西之间的适配器的一部分,那将是有用的,这需要一个1D一。

6 个答案:

答案 0 :(得分:2)

你不能,在C#中用这种方式转换数组是不可能的。您可以通过使用外部DLL(C / C ++)来实现,但是您需要将阵列保持在固定位置。

速度

一般来说,我会建议避免使用2D数组,因为C#的速度很慢,更好地使用锯齿状数组,甚至更好的单维数据,只需要一点点数学。

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

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

答案 1 :(得分:2)

在C#中,无法动态调整数组大小。一种方法是使用System.Collections.ArrayList而不是本机数组。另一个(更快)的解决方案是重新分配具有不同大小的数组,并将旧数组的内容复制到新数组。通用函数resizeArray(下面)可用于执行此操作。

这里有一个例子:

// Reallocates an array with a new size, and copies the contents
// of the old array to the new array.
// Arguments:
//   oldArray  the old array, to be reallocated.
//   newSize   the new array size.
// Returns     A new array with the same contents.
public static System.Array ResizeArray (System.Array oldArray, int newSize) {
   int oldSize = oldArray.Length;
   System.Type elementType = oldArray.GetType().GetElementType();
   System.Array newArray = System.Array.CreateInstance(elementType,newSize);
   int preserveLength = System.Math.Min(oldSize,newSize);
   if (preserveLength > 0)
      System.Array.Copy (oldArray,newArray,preserveLength);
   return newArray; }

答案 2 :(得分:2)

你已经可以迭代一个multidim,好像它是一维数组:

  int[,] data = { { 1, 2, 3 }, { 3, 4, 5 } };

  foreach (int i in data)
     ...  // i := 1 .. 5

你可以在一个类中包含一个1-dim数组,并提供一个索引器属性this[int x1, int x2]

但其他一切都需要不安全的代码或复制。两者都效率低下。

答案 3 :(得分:1)

骑在Felix K.的答案后面并引用一位开发人员的话:

  

您无法在不丢失信息的情况下将广场转换为广场

答案 4 :(得分:0)

int[,] x = {{1, 2}, {2, 2}};
int[] y = new int[4];
System.Buffer.BlockCopy(x, 0, y, 0, 4);

答案 5 :(得分:0)

你不能施放,你必须复制元素:

int[] y = (from int i in y select i).ToArray();
相关问题