Difference between BinaryWriter and BinaryFormatter.Serialize?

强颜欢笑 提交于 2020-12-05 08:26:09

问题


I'm new to object serialization, and in the course of my learning how to read from and write to a file (deserialize and serialize) using BinaryFormatter, I came across BinaryReader and BinaryWriter, which seemed to be doing the same thing.

Is there some subtle difference between BinaryFormatter.Serialize() and BinaryWriter? Or is BinaryWriter just a more compact way performing the the same action as BinaryFormatter.Serialize()?


回答1:


BinaryWriter is used to write primitive types in binary to a stream and supports writing strings in a specific encoding. BinaryFromatter is responsible for serializing an entire object or graph of connected objects into binary format. So, I suppose you can say BinaryWriter is a much more elementary form of something like BinaryFormatter.

I got this information here: BinaryWriter & BinaryFormatter




回答2:


BinaryWriter and BinaryFormatter are two different thing.

BinaryFormatter is used for serialization. It helps you to map a C# object to a binary representation which you can write to a file, a network stream etc.

But BinaryWriter does not help you map the C# object to binary data. It just gives you the ability to write binary data (as the name implies). So you give it primitive types like an int, it converts it into binary and write it. After writing when you need reading it you have to use a BinaryReader and you must know somehow that you have to read an int. So you have to serialize your data somehow yourself.

You can say BinaryFormatter uses BinaryWriter to be able to write binary data but it does a lot of other jobs to automatically serialize and deserialize your object.



来源:https://stackoverflow.com/questions/40749926/difference-between-binarywriter-and-binaryformatter-serialize

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