我们有一个传统类A,它是[Serializable],但不是ISerializable
由于其他原因,必须修补此类以实现ISerializable。

问题是我们仍然需要能够加载旧的保存文件,该文件使用.NET的默认实现对类A进行序列化。
换句话说,在加载旧的保存文件时,必须像旧版本一样反序列化类A,然后将其转换为类A的新版本,以便再次保存时,将使用我们新的ISerializable实现。

修补类A而不破坏向后兼容性的最合适方法是什么?

最佳答案

解决方案1

首先,更改项目的程序集版本。

// AssemblyInfo.cs:
[assembly: AssemblyVersion("2.0.0.0")]


为保存游戏数据创建一个新类型。

// The legacy savegame data. Keep it as it is.
[Serializable]
public class Savegame
{
    // ... the legacy fields
}

// The new savegame data. This implements ISerializable
[Serializable]
public class SavegameNew : Savegame, ISerializable
{
    // this constructor will execute on deserialization. You will deserialize
    // both the legacy and new types here.
    private SavegameNew(SerializationInfo info, StreamingContext context)
    {
        foreach (SerializationEntry entry in info)
        {
            // you can iterate the serialized elements like this
            // if this is a new format you will get the new elements, too
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        // custom serialization of the new type
    }
}


现在,您需要一个绑定程序类,它将旧格式映射到新格式:

internal class SavegameBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        // Of course, use the assembly version of the old version here.
        // You don't even need to change the assembly version, though than can lead to ambiguity
        AssemblyName asmName = new AssemblyName(assemblyName);
        if (asmName.Version == new Version(1, 0, 0, 0) && typeName == typeof(Savegame).FullName)
            return typeof(SavegameNew);

        // otherwise we do not change the mapping
        return null;
    }
}


您可以像这样使用它:

// the saveStream can contain either the old other the new format
BinaryFormatter bf = new BinaryFormatter() { Binder = new SavegameBinder() };
SavegameNew data = (SavegameNew)bf.Deserialize(saveStream);


解决方案2

使用此解决方案,您无需将Savegame映射到SavegameNew。如果不更改程序集版本,则甚至不需要绑定程序类。

如果更改了程序集版本,则SavegameBinder应返回新程序集的Savegame类型。旧版Savegame应该实现IObjectReference接口,因此一旦将其反序列化,它就可以返回SavegameNew实例。

// The legacy savegame data
[Serializable]
public class Savegame: IObjectReference
{
    // ... the legacy fields

    public object GetRealObject(StreamingContext context)
    {
        return new SavegameNew(...);
    }
}

关于c# - 如何用新的ISerializable类替换旧类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33544378/

10-09 00:09