C# 用 BinaryFormatter 存float 数组
时间: 2024-09-27 14:08:58 浏览: 50
在C#中,`BinaryFormatter`是一个序列化工具,用于将.NET对象转换成字节流以便存储或在网络上传输。如果你想要使用`BinaryFormatter`来保存`float`数组,你需要按照以下步骤操作:
1. 创建一个`float`数组:
```csharp
float[] floatArray = new float[5] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
```
2. 获取一个`Stream`(如内存流`MemoryStream`),用于存储序列化的数据:
```csharp
using (MemoryStream ms = new MemoryStream())
{
// 序列化操作
}
```
3. 使用`BinaryFormatter`进行序列化:
```csharp
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, floatArray);
```
这里,`formatter.Serialize`方法接收`Stream`和要序列化的对象。
4. 若要还原(反序列化)数据,你可以这样做:
```csharp
// 从存储位置读取数据
ms.Seek(0, SeekOrigin.Begin);
float[] deserializedArray;
using (Stream stream = ms)
{
deserializedArray = (float[])formatter.Deserialize(stream);
}
```
现在,`deserializedArray`将包含原始序列化的`float`数组。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)