如何快速保存/加载类的实例到文件 [英] How to quickly save/load class instance to file
问题描述
我在我的应用程序的类/结构的几个系列。
I have several collections of classes/structs in my app.
类只是一个类的字段
class A
{
public int somevalue;
public string someothervalue
}
和我的收藏
List<A> _myList;
我需要能够保存_myList和负载。我只是想保存所有类字段到文件并加载。我不想花时间写我自己的保存/载入。是否有.NET任何工具来帮助我。我不关心文件格式。
I need to be able to save _myList and load. I just want to save all class fields to file and load. I don't want to spend time writing my own save/load. Are there any tools in .NET to help me. I don't care about the file format.
推荐答案
XMLSerializer的是不是很难使用。只要你的对象并不大,这是pretty的快。序列化出一些巨大的物体在我的几个应用程序。它永远和生成的文件几乎是100兆,但他们可编辑的我应该需要调整一些东西。再加上它并不重要,如果我将字段添加到我的对象。对象的旧版本的序列化的文件仍然反序列化正确。我做一个单独的线程序列化,因此它不会不管需要我的情况有多长。需要说明的是,你的 A
类必须有一个构造XMLSerialziation工作。
XMLSerializer isn't hard to use. As long as your objects aren't huge, it's pretty quick. I serialize out some huge objects in a few of my apps. It takes forever and the resulting files are almost 100 megs, but they're editable should I need to tweak some stuff. Plus it doesn't matter if I add fields to my objects. The serialized files of the older version of the object still deserialize properly.. I do the serialization on a separate thread so it doesn't matter how long it takes in my case. The caveat is that your A
class has to have a constructor for XMLSerialziation to work.
下面是一些工作code我用序列化/反序列化的错误处理拆出来的可读性...
Here's some working code I use to serialize/deserialize with the error handling ripped out for readibility...
private List<A> Load()
{
string file = "filepath";
List<A> listofa = new List<A>();
XmlSerializer formatter = new XmlSerializer(A.GetType());
FileStream aFile = new FileStream(file, FileMode.Open);
byte[] buffer = new byte[aFile.Length];
aFile.Read(buffer, 0, (int)aFile.Length);
MemoryStream stream = new MemoryStream(buffer);
return (List<A>)formatter.Deserialize(stream);
}
private void Save(List<A> listofa)
{
string path = "filepath";
FileStream outFile = File.Create(path);
XmlSerializer formatter = new XmlSerializer(A.GetType());
formatter.Serialize(outFile, listofa);
}
这篇关于如何快速保存/加载类的实例到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!