首页 > 解决方案 > 更新二进制序列化类 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;
        }
    }

}

标签: c#.netserializationbinaryformatter

解决方案


由 实现的二进制序列化System.Runtime.Serialization.Formatters.Binary是一种无模式的二进制格式。这意味着如果序列化程序看到一个int字段,它会在文件中写入 4 个字节,与所有其他支持的类型相同。它非常快,但不灵活。

这与也写入模式的序列化程序不同,后者将写入 4 个字节以及字段名称,因此稍后反序列化程序可以混合和匹配。正如您可以想象的那样,它速度较慢但更灵活。

只要您坚持使用前者,就不要更改架构。你没有什么可以用它做的。

这就是为什么每个人都将(并且已经)推荐使用模式序列化程序的原因,例如 JSON、BSON(二进制 json)、Google 的 proto-buf、XML、Sql 或 Nosql 数据库,以及其他任何东西,尤其是在类模式的开发过程中经常改变。


推荐阅读