我有一个文件,并且需要随机序列化多个对象.我该如何使用C#? [英] I have a Single File And need to serialize multiple objects randomly. How can I in c#?
问题描述
我只有一个文件,创建新对象时需要序列化同一类的多个对象.我无法将它们存储在数组中,因为我需要在创建对象的实例中序列化它们.请帮我.
I have a single file and need to serialize multiple objects of the same class when ever a new object is created. I can't store them in arrays as I need to serialize them the instance an object is create. Please, help me.
推荐答案
您正在使用哪种序列化机制?由于根节点和名称空间声明之类的东西, XmlSerializer
可能是一个问题,要获取它有点棘手-而且它不适用于部分反序列化. BinaryFormatter
首先非常脆弱-在大多数情况下,我不建议这样做.
What serialization mechanism are you using? XmlSerializer
might be a problem because of the root node and things like namespace declarations, which are a bit tricky to get shot of - plus it isn't great at partial deserializations. BinaryFormatter
is very brittle to begin with - I don't recommend it in most cases.
一个选项可能是 protobuf-net ;这是一个二进制序列化程序(使用Google的协议缓冲区"格式-高效,可移植且具有版本兼容性).您可以使用 Serializer.SerializeWithLengthPrefix
将多个对象序列化为流.要反序列化相同的项目, Serializer.DeserializeItems
返回反序列化项目的 IEnumerable< T>
-或者您可以轻松地将 TryDeserializeWithLengthPrefix
公开(目前是私有的,但来源可用).
One option might be protobuf-net; this is a binary serializer (using Google's "protocol buffers" format - efficient, portable, and version-tolerant). You can serialize multiple objects to a stream with Serializer.SerializeWithLengthPrefix
. To deserialize the same items, Serializer.DeserializeItems
returns an IEnumerable<T>
of the deserialized items - or you could easily make TryDeserializeWithLengthPrefix
public (it is currently private, but the source is available).
创建对象后,只需将每个对象写入文件-完成工作即可.
Just write each object to file after you have created it - job done.
如果您想举一个例子,请说-尽管该单元测试了此处进行概述.
If you want an example, please say - although the unit tests here give an overview.
基本上是(未经测试)
using(Stream s = File.Create(path))
{
Serializer.SerializeWithLengthPrefix(s, command1, PrefixStyle.Base128, 0);
... your code etc
Serializer.SerializeWithLengthPrefix(s, commandN, PrefixStyle.Base128, 0);
}
...
using(Stream s = File.OpenRead(path)) {
foreach(Command command in
Serializer.DeserializeItems<Command>(s, PrefixStyle.Base128, 0))
{
... do something with command
}
}
这篇关于我有一个文件,并且需要随机序列化多个对象.我该如何使用C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!