多个对象序列化和反序列化

来源:百度知道 编辑:UC知道 时间:2024/05/17 22:48:51
假设有一个account类,现要求实现
1.将一个account类数组中的多个对象保存到txt文件中,
2.从文件中读出各对象保存到数组中。
请着重写清读的时候怎么从文件中读出一个一个的对象。
知道用序列化和反序列化,就请大侠们从这方面教教.
麻烦用二进制序列化和反序列化,谢谢。
1楼大侠能不能再写下

没什么好说的,写个例子给你看吧,有些代码用了VS2008的特性,如果你用的是VS2008以下的版本,自己改下吧。

using System;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Demo
{

public class Account
{
public int UserID { get; set; }
public string Username { get; set; }
}

class Program
{
static void Main( string[] args )
{
Account[] accounts = {
new Account(){ UserID = 1, Username = "test1" },
new Account(){ UserID = 2, Username = "test2" },
new Account(){ UserID = 3, Username = "test3" }
};

string savePath = @"c:\XmlSerializerTest.txt";
XmlSerializer xs = new XmlSerializer( typeof( Account[] ) );
using ( TextWriter tw = new StreamWriter( savePath ) )
{
xs.Serialize( tw, accounts );
tw.Close();
using ( TextReader tr = new StreamReader( savePath ) )
{
Account[] d