对象序列化编程的基本步骤为;首先用Serialzable属性把包含数据的类标记为可序列化的类,如果期中某个成员不需要序列化,则使用NonSerialized来标识。然后调用BinaryFomatter或Soapformatter的Serialize方法实现对象的序列化,反序列化时,则调用Deserialize方法。
[Serializable]//指示学生类是可序列化的类
public class Student
{
public int sno;
public string name;
public bool sex;
public Student(int sno, string name, bool sex)
{
this.sno = sno;
this.name = name;
this.sex = sex;
}
}
[Serializable]//指示学生列表是可序列化的类
public class StudentList
{
private Student[] list = new Student[100];
public Student this[int index]//索引器
{
get
{
if (index < 0 || index >= 100)//检查索引范围
return list[0];
else
return list[index];
}
set
{
if (!(index < 0 || index >= 100))
list[index] = value;
}
}
}
public partial class Myfile04 : Form
{
private StudentList list = new StudentList();//声明一个学生列表
private int i = 0;//i用来标记加入到列表中学生的下标,也代表学生的个数
public Myfile04()
{
InitializeComponent();
}
[Serializable]//指示学生类是可序列化的类
public class Student
{
public int sno;
public string name;
public bool sex;
public Student(int sno, string name, bool sex)
{
this.sno = sno;
this.name = name;
this.sex = sex;
}
}
[Serializable]//指示学生列表是可序列化的类
public class StudentList
{
private Student[] list = new Student[100];
public Student this[int index]//索引器
{
get
{
if (index < 0 || index >= 100)//检查索引范围
return list[0];
else
return list[index];
}
set
{
if (!(index < 0 || index >= 100))
list[index] = value;
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
int sno = Int32.Parse(txtSno.Text);
bool isMale;
if (rdoMale.Checked) isMale = true;
else isMale = false;
Student student = new Student(sno,txtName.Text,isMale);
list[i] = student;//将学生添加到学生的列表中
i++;
}
private void btnSave_Click(object sender, EventArgs e)
{
string file = @"d:\data\stu.dat";
Stream stream= new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
BinaryFormatter bf = new BinaryFormatter();//创建序列化对象
bf.Serialize(stream,list);//将list学生列表序列化并写入
stream.Close();
}
private void btnShow_Click(object sender, EventArgs e)
{
lstShow.Items.Clear();//清除重置
lstShow.Items.Add("学号\t姓名\t性别");
string file=@"d:\data\stu.dat";
Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read );
BinaryFormatter bf = new BinaryFormatter();//创建序列化对象
StudentList students=(StudentList)bf.Deserialize(stream);//把流反序列化
int k = 0;
while (students[k] != null)//逐个显示学生信息
{
int sno = students[k].sno;
string name = students[k].name;
bool isMale = students[k].sex;
string sex ="";
if (isMale) sex = "男";
else sex = "女";
string result = string.Format("{0}\t{1}\t{2}",sno,name,sex);
lstShow.Items.Add(result);
k++;
}
stream.Close();
}
}