C# - 将字节数组转换为结构数组,反之亦然(相反)

作者:编程家 分类: arrays 时间:2025-09-29

将字节数组转换为结构数组与反之:C#中的操作指南

在C#编程中,有时候我们需要在字节数组和结构数组之间进行转换。这样的操作在处理二进制数据时特别有用,例如在网络通信或者文件IO中。本文将介绍如何在C#中进行这两种转换,以及通过简单的案例代码演示它们的用法。

### 将字节数组转换为结构数组

首先,让我们看一下如何将字节数组转换为结构数组。这在接收二进制数据时非常有用,例如从网络或文件中读取数据。

csharp

// 定义一个结构

struct MyStruct

{

public int ID;

public float Value;

}

class Program

{

static void Main()

{

// 创建一个字节数组

byte[] byteArray = { 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0 };

// 计算结构的大小

int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(MyStruct));

// 计算结构数组的长度

int structCount = byteArray.Length / size;

// 将字节数组转换为结构数组

MyStruct[] structArray = new MyStruct[structCount];

for (int i = 0; i < structCount; i++)

{

IntPtr ptr = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(byteArray, i * size);

structArray[i] = (MyStruct)System.Runtime.InteropServices.Marshal.PtrToStructure(ptr, typeof(MyStruct));

}

// 现在structArray包含了转换后的结构数组

}

}

### 将结构数组转换为字节数组

相反地,有时我们需要将结构数组转换回字节数组。这在数据发送时非常有用,例如将结构化数据发送到网络或写入文件。

csharp

class Program

{

static void Main()

{

// 定义一个结构数组

MyStruct[] structArray = new MyStruct[2];

structArray[0] = new MyStruct { ID = 1, Value = 2.0f };

structArray[1] = new MyStruct { ID = 3, Value = 4.0f };

// 计算结构的大小

int size = System.Runtime.InteropServices.Marshal.SizeOf(typeof(MyStruct));

// 将结构数组转换为字节数组

byte[] byteArray = new byte[structArray.Length * size];

for (int i = 0; i < structArray.Length; i++)

{

IntPtr ptr = System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(byteArray, i * size);

System.Runtime.InteropServices.Marshal.StructureToPtr(structArray[i], ptr, false);

}

// 现在byteArray包含了转换后的字节数组

}

}

在C#中,将字节数组转换为结构数组或者反之是一种常见的操作,特别是在处理二进制数据时。通过使用`System.Runtime.InteropServices.Marshal`类,我们可以方便地进行这两种转换。这些操作对于网络通信、文件IO以及其他需要处理二进制数据的场景非常有用。希望本文的示例代码能够帮助你更好地理解和应用这些转换操作。