将对象列表写入文件 [英] write list of objects to a file
问题描述
我有以下格式的班级推销员:
I've got a class salesman in the following format:
class salesman
{
public string name, address, email;
public int sales;
}
我有另一个类,用户可以在其中输入姓名、地址、电子邮件和销售额.然后将此输入添加到列表中
I've got another class where the user inputs name, address, email and sales. This input is then added to a list
List<salesman> salesmanList = new List<salesman>();
在用户将尽可能多的销售员输入列表后,他们可以选择将列表保存到他们选择的文件中(我可以将其限制为 .xml 或 .txt(哪个更合适)).我如何将此列表添加到文件中?此外,如果用户希望稍后查看记录,则需要将该文件重新读回列表中.
After the user has input as many salesman to the list as they like, they have the option to save the list to a file of their choice (which I can limit to .xml or .txt(which ever is more appropriate)). How would I add this list to the file? Also this file needs to be re-read back into a list if the user wishes to later view the records.
推荐答案
这样的事情会起作用.这使用二进制格式(加载速度最快),但相同的代码适用于具有不同序列化程序的 xml.
Something like this would work. this uses a binary format (the fastest for loading) but the same code would apply to xml with a different serializer.
using System.IO;
[Serializable]
class salesman
{
public string name, address, email;
public int sales;
}
class Program
{
static void Main(string[] args)
{
List<salesman> salesmanList = new List<salesman>();
string dir = @"c: emp";
string serializationFile = Path.Combine(dir, "salesmen.bin");
//serialize
using (Stream stream = File.Open(serializationFile, FileMode.Create))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bformatter.Serialize(stream, salesmanList);
}
//deserialize
using (Stream stream = File.Open(serializationFile, FileMode.Open))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
List<salesman> salesman = (List<salesman>)bformatter.Deserialize(stream);
}
}
}
这篇关于将对象列表写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!