.net binary formatter deserialize an object whose definition has changed a lot

余生颓废 提交于 2020-01-21 12:15:28

问题


I am trying to deserialize a file which is serialized using an older version.

In the new version, We have done the following things

  1. change namespace
  2. Change class member access level, from private to public
  3. Add a new inter parent class. Class A was derived from Base. Now, Class A is derived from B, and B is derived from Base. In B, there is no new member introduced.
  4. Base class adds a new member.

I know using SerializationBinder can solve issue 1. For the new added class member, I have marked with [NonSerialized]. But I still get deserialization error.

Any pointers?


回答1:


I hate to say it, but my first pointer here would be "don't do that" - BinaryFormatter is very brittle - and while you can often bang your head on the keyboard for 6 hours to get past each successive pain point, it really isn't worth it. There are many many reasons I always say "don't use BinaryFormatter" - you've sadly found 4 of them. Frankly, my recommendation would be:

  • put back the original class, and use it just as a DTO to deserialize the old data
  • start moving to a model where you have a separate DTO model and entity model - and map between them so that your serialization is entirely independent of your application logic
  • investigate different serializers; just about any alternative serializer would be preferable to BinaryFormatter (except perhaps NetDataContractSerializer, which goes and repeats all the same mistakes; DataContractSerializer is ok-ish, though)

Sorry that isn't more positive...



来源:https://stackoverflow.com/questions/26205347/net-binary-formatter-deserialize-an-object-whose-definition-has-changed-a-lot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!