Serialization and object versioning in C#

前端 未结 1 588
慢半拍i
慢半拍i 2021-02-05 17:55

If I want to serialize an object I have to use [Serializable] attribute and all member variables will be written to the file. What I don\'t know how to do versionin

相关标签:
1条回答
  • 2021-02-05 18:24

    Forgive me if some of what I write is too obvious,

    First of all, please! you must stop thinking that you are serializing an object... That is simply incorrect as the methods which are part of your object are not being persisted. You are persisting information - and so.. DATA only.

    .NET serialization also serializing the type name of your object which contain the assembly name and its version, so when you deserialize - it compares the persisted assembly information with the type that will be manifested with the information - if they are not the same it will return an exception.

    Beside the versioning problem - not everything can be serialized so easily.. try to serialize a System.Drawing.Color type and you will begin to understand the problems with the over simplistic mechanism of .NET serialization.

    Unless you plan to serialize something really simple which has no plans to evolve I wouldn't use the serialization mechanism provided by .NET.

    Getting the focus back to your question, you can read here about the versioning ignorance ability: http://msdn.microsoft.com/en-us/library/ms229752(v=vs.80).aspx which is provided for BinaryFormatter.

    You should also check XML Serialization which has some nice abilities, but the biggest benefit is that you getting an XML which is Human readable so your data will never be lost even if you had complication with the versioning of your types.

    But finally, I recommend you either use Database with Entity Framework to persist your data or write your own flat file manager.. while EF is very good for most solutions, sometime you might want something lighter to persist something very simple. (my imply is that I can no longer see a solution where .NET serialization can be relevant.)

    I hope this helps, Good luck.

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