在 C# 中,如何序列化 Queue<>? (.Net 2.0)
在 XmlSerializer 构造函数行中,下面的代码会导致 InvalidOperationException,该异常还抱怨没有为泛型类型实现默认访问器。
Queue<MyData> myDataQueue = new Queue<MyData>();
// Populate the queue here
XmlSerializer mySerializer =
new XmlSerializer(myDataQueue.GetType());
StreamWriter myWriter = new StreamWriter("myData.xml");
mySerializer.Serialize(myWriter, myDataQueue);
myWriter.Close();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从队列中序列化数据会更容易(而且在我看来更合适) - 可能是在平面数组或
List
中。 由于Queue
实现了IEnumerable
,您应该能够使用:It would be easier (and more appropriate IMO) to serialize the data from the queue - perhaps in a flat array or
List<T>
. SinceQueue<T>
implementsIEnumerable<T>
, you should be able to use:并非框架的所有部分都是为 XML 序列化而设计的。 你会发现连载部门也缺少字典。
队列的实现非常简单。 您可以轻松创建自己的 IList,以便它可以序列化。
Not all parts of the framework are designed for XML serialization. You'll find that dictionaries also are lacking in the serialization department.
A queue is pretty trivial to implement. You can easily create your own that also implements IList so that it will be serializable.
如果你想使用内置的序列化,你需要遵守它的规则,这意味着默认的构造函数,以及你想要序列化(并且可能是反序列化)的成员的公共 get/set 属性
您要序列化的数据类型 (MyData)
if you want to use the built in serialization you need to play by its rules, which means default ctor, and public get/set properties for the members you want to serialize (and presumably deserialize )
on the data type you want to serialize (MyData)
就我而言,我有一个动态队列,我必须保存和加载该队列的状态。
使用 Newtonsoft.Json:
In my case i had a dynamic queue and i had to save and load the state of this one.
Using Newtonsoft.Json: