Maintain .NET Serialized data compatability when moving classes

前端 未结 1 1576
孤独总比滥情好
孤独总比滥情好 2020-12-10 21:34

I have data that\'s been serialized. The classes associated with the serialized data is part of a large legacy project which has a number of 3rd party references which are

相关标签:
1条回答
  • 2020-12-10 22:17

    You need to implement a custom SerializationBinder. Override the BindToType method to select the type to load based on its name:

    public override Type BindToType(string assemblyName, string typeName)
    {
        if (assemblyName == "MyOldAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
        {
            if (typeName == "MyOldNamespace.MyOldClass")
            {
                return typeof(MyNewClass);
            }
        }
        // Fall back to the default behavior, which will throw
        // a SerializationException if the old assembly can't be found
        return null;
    }
    

    (this is a very basic implementation, in a real-world scenario you would probably use a better mapping logic).

    You can also override BindToName if you need to reserialize the data so that it can still be read by the old assembly. This allows you to customize the assembly and type name of the serialized object.

    Once you have your custom SerializationBinder, you just need to assign it to the Binder property of the formatter, and use it normally from there.

    If you need to change the structure of the types (add or rename fields, change types...), you will need to implement a ISerializationSurrogate to map the old data to the new type structure.

    0 讨论(0)
提交回复
热议问题