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();
}
}
}
运行结果: