Where exactly does serialization comes into the picture? I read about serializtion on the 'net and I have come to know that
它是一个接口,如果在类中实现,意味着它可以被不同的序列化器自动序列化和反序列化.
给我一个很好的理由,为什么以及什么时候需要序列化一个类?假设一旦序列化,究竟发生了什么?
Chr*_*ich 25
只要对象需要持久化或传输超出其存在范围,就需要进行序列化.
持久性是指在某处保存对象并在以后以相同状态加载对象的能力.例如:
Transmission is the ability to send an object outside of its original scope to some receiver. For example:
For each of these, there must be some serial bit representation that can be stored, communicated, and then later used to reconstitute the original object. The process of turning an object into this series of bits is called "serialization", while the process of turning the series of bits into the original object is called "deserialization".
The actual representation of the object in serialized form can differ depending on what your goals are. For example, in C#, you have both XML serialization (via the XmlSerializer class) and binary serialization (through use of the BinaryFormatter class). Depending on your needs, you can even write your own custom serializer to do additional work such as compression or encryption. If you need a language- and platform-neutral serialization format, you can try Google's Protocol Buffers which now has support for .NET (I have not used this).
上面提到的XML表示适用于以标准格式存储对象,但根据您的需要,它可能是冗长和缓慢的.二进制表示节省了空间,但不像XML那样可以跨语言和运行时移植.重要的是串行器和解串器必须相互理解.当您开始引入向后和向前兼容性和版本控制时,这可能是一个问题.
潜在的序列化兼容性问题的示例:
Foo对象序列化为文件.Foo到文件中.Foo.如果版本2.0 Foo具有版本1.0 Foo没有的其他属性,这可能很麻烦.您必须明确不支持此方案,或者在序列化方面有一些版本控制故事..NET可以为您做一些这样的事情.在这种情况下,您可能还有相反的问题:用户可能会尝试Foo使用您的程序的1.0 版打开2.0版文件.
我自己没有使用过这些技术,但.NET 2.0及更高版本支持版本容忍序列化以支持向前和向后兼容:
- 容忍无关或意外的数据.这使该类型的较新版本能够将数据发送到旧版本.
- 容忍丢失的可选数据.这使旧版本可以将数据发送到更新的版本.
- 序列化回调.这样可以在缺少数据的情况下设置智能默认值.