use*_*285 8 c# arrays type-conversion multidimensional-array
我在C#中将2维数组转换为单维数据.我从设备(C++)接收二维数组,然后在C#中将其转换为1维.这是我的代码:
int iSize = Marshal.SizeOf(stTransactionLogInfo); //stTransactionLogInfo is a structure
byte[,] bData = (byte[,])objTransLog; //objTransLog is 2 dimensionl array from device
byte[] baData = new byte[iSize];
for (int i = 0; i < bData.GetLength(0); i++)
{
for (int j = 0; j < iSize; j++)
{
baData[j] = bData[i, j];
}
}
Run Code Online (Sandbox Code Playgroud)
我从上面的代码中得到了所需的结果,但问题是它不是标准的实现方式.我想知道如何以标准方式完成.可能正在进行编组,我不确定.提前致谢.
dtb*_*dtb 16
您可以使用Buffer.BlockCopy方法:
byte[,] bData = (byte[,])objTransLog;
byte[] baData = new byte[bData.Length];
Buffer.BlockCopy(bData, 0, baData, 0, bData.Length);
Run Code Online (Sandbox Code Playgroud)
例:
byte[,] bData = new byte[4, 3]
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};
byte[] baData = new byte[bData.Length];
Buffer.BlockCopy(bData, 0, baData, 0, bData.Length);
// baData == { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }
Run Code Online (Sandbox Code Playgroud)
最简单的方法
int iSize = Marshal.SizeOf(stTransactionLogInfo); //stTransactionLogInfo is a structure
byte[,] bData = (byte[,])objTransLog; //objTransLog is 2 dimensionl array from device
byte[] baData = bData.Cast<byte>().ToArray();
Run Code Online (Sandbox Code Playgroud)