c# - 更新二进制序列化类 c# .NET 的属性会有效地破坏文件
问题描述
我创建了一个 Car 类,我用它来存储 Cars 的所有各种属性的预设序列化版本以及你有什么。
随着程序的进行,我已经意识到,如果我添加或删除 Car 的属性,则以前的每个序列化文件现在都无法读取。可以想象,这是一个问题。
如何在不使所有以前的文件失效的情况下更新我的课程?
-- 可点击
更新:我添加了我正在做的代码示例如果我添加/删除属性并尝试反序列化文件,则会出现问题。
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using System;
namespace MyCars
{
[Serializable]
public class Car
{
public string Name { get; set; }
public double TopSpeed { get; set; }
public Car(string name, double topspeed)
{
Name = name;
TopSpeed = topspeed;
}
}
public static class Serializer
{
public static bool LoadCar(string filePath, out Car car)
{
Stream TestFileStream = File.OpenRead(filePath);
BinaryFormatter serializer = new BinaryFormatter();
try
{
car = (Car)serializer.Deserialize(TestFileStream);
}
catch (Exception ex)
{
Console.WriteLine("Could not deserialize");
TestFileStream.Close();
car = null;
return false;
}
return true;
}
public static bool SaveCar(string filePath, Car car)
{
Stream TestFileStream = File.Create(filePath);
BinaryFormatter serializer = new BinaryFormatter();
serializer.Serialize(TestFileStream, car);
TestFileStream.Close();
return true;
}
}
}
解决方案
由 实现的二进制序列化System.Runtime.Serialization.Formatters.Binary
是一种无模式的二进制格式。这意味着如果序列化程序看到一个int
字段,它会在文件中写入 4 个字节,与所有其他支持的类型相同。它非常快,但不灵活。
这与也写入模式的序列化程序不同,后者将写入 4 个字节以及字段名称,因此稍后反序列化程序可以混合和匹配。正如您可以想象的那样,它速度较慢但更灵活。
只要您坚持使用前者,就不要更改架构。你没有什么可以用它做的。
这就是为什么每个人都将(并且已经)推荐使用模式序列化程序的原因,例如 JSON、BSON(二进制 json)、Google 的 proto-buf、XML、Sql 或 Nosql 数据库,以及其他任何东西,尤其是在类模式的开发过程中经常改变。
推荐阅读
- arrays - 将多个对象传递到数组时,VBScript 将多个对象设置为 Nothing 不起作用
- node.js - await 不等待函数结束
- ios - 导入 Firebase 以在物理设备上使用时出错
- sql - 在 Case 语句中使用列别名作为表的其他列中的值
- java - 在 Android Studio (Java) 上创建注册页面
- android - Unity突然FPS下降
- java - Spring:创建在类路径资源中定义的名称为“entityManagerFactory”的bean时出错
- r - 按组转置两个变量
- java - 如何通过 wifi 与 REV 机器人控制中心通信?
- c - 将 uint8_t 便携式重新解释为 int8_t 并强制补码