Deserialization backwards compatibility

前端 未结 5 1349
刺人心
刺人心 2020-12-05 15:08

I am trying to deserialize \"SomeClass\" with an older version of an application. I get this below exception

System.Runtime.Serialization.Serializatio

5条回答
  •  醉话见心
    2020-12-05 15:45

    First, never NEVER use the CLR's serialization functions for anything that resembles long-term storage. We make that mistake usually once, put objects in a blob database field and pat ourselves in the back thinking we're clever. And then the CLR gets a patch or our assemblies change versions and you're screwed. So don't do it.

    If you still want to do it, the best way to manage the problem is to create your own SerializationBinder that looks something like this:

    public sealed class CustomBinder : SerializationBinder {
    
        public override Type BindToType(string assemblyName, string typeName) {
    
            Type typeToDeserialize = null;
    
            if (typeName.IndexOf("SomeType") != -1) {
                typeToDeserialize = typeof(Foo.Bar.Bax.NewType);
            }
            else if (typeName.IndexOf("SomeOtherType") != -1) {
                typeToDeserialize = typeof(Foo.Bar.Bax.SomeOtherNewType);
            }
            else {
                // ... etc
            }
    
            return typeToDeserialize;
        }
    }
    

    Set the Binder property of the formatter you're using prior to deserializing so that it overrides the defaults.

    Note that I'm not offering a drop-in solution here, I'm recommending how to solve the problem. Once you've converted out of whatever you're doing, investigate other serialization technologies like protobuf, or write your own. Either way you should never rely on the CLR for long-term serialization support.

提交回复
热议问题