C#中对数组序列化与反序列化
时间: 2024-12-02 14:22:13 浏览: 84
在C#中,数组也可以被序列化和反序列化,这对于保存数据以便于后续恢复非常有用。C#提供了`System.Runtime.Serialization.Formatters.Binary.BinaryFormatter`类来完成这项任务。以下是基本步骤:
**序列化数组:**
1. 创建一个`BinaryFormatter`实例。
2. 使用`Serialize`方法,传入数组对象和文件流(或者是内存流`MemoryStream`)来保存数组到磁盘或内存。
```csharp
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
byte[] arrayBytes;
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, yourArray); // 替换yourArray为你想要序列化的数组
arrayBytes = stream.ToArray(); // 现在你有了序列化的字节数组
```
**反序列化数组:**
1. 创建一个`MemoryStream`或`FileStream`,并将序列化的字节数组传递给它。
2. 再次创建`BinaryFormatter`实例,并使用`Deserialize`方法从流中读取并重构数组。
```csharp
stream = new MemoryStream(arrayBytes);
formatter = new BinaryFormatter();
yourDeserializedArray = (T[])formatter.Deserialize(stream); // T是你数组的实际类型
```
需要注意的是,在使用`BinaryFormatter`时,它会保留数组的所有元信息,包括数组长度和元素类型,因此能准确地还原原始结构。
阅读全文
相关推荐















