您的位置:首页 > 编程语言 > C#

C# ArrayList用BinaryFormatter序列化和反序列化进行文件读写的一个简单例子

2011-04-22 11:04 826 查看
using System;

using System.Collections;

using System.Linq;

using System.Text;

using System.IO; //文件读写的IO空间

using System.Runtime.Serialization.Formatters.Binary; //BinaryFormatter序列化需要的空间

//Person类

namespace Serializable

{

[Serializable] //可序列化的声明,一定要有,不然无法序列化

class Person

{

private String name;

private String sex;

private int age;

public Person(String n, String s, int a)

{

name = n;

sex = s;

age = a;

}

public String Name

{

get

{

return name;

}

set

{

name = value;

}

}

public String Sex

{

get

{

return sex;

}

set

{

sex = value;

}

}

public int Age

{

get

{

return age;

}

set

{

age = value;

}

}

}

}

//主运行程序

namespace Serializable

{

class Program

{

static void Main(string[] args)

{

Person p1 = new Person("张三", "男", 20);

Person p2 = new Person("John", "男", 20);

ArrayList al = new ArrayList();

al.Add(p1);

al.Add(p2);

//序列化

try

{

FileStream fs = new FileStream("serialiable.bin", FileMode.Create);

BinaryFormatter bf = new BinaryFormatter();

bf.Serialize(fs, al);

fs.Close();

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

}

Console.WriteLine("序列化成功!");

Console.Read();

//反序列化

try

{

FileStream fs = new FileStream("serialiable.bin", FileMode.Open, FileAccess.Read);

BinaryFormatter bf = new BinaryFormatter();

ArrayList all = (ArrayList)bf.Deserialize(fs);

foreach (Person p in all)

{

Console.WriteLine(p.Name + p.Sex + p.Age);

}

}

catch (Exception e)

{

Console.WriteLine(e.Message);

}

Console.Read();

Console.Read();

}

}

}

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐