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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…