序列化反序列化:
序列化:串行化 对象持久化 将对象存储到文件或数据库的字段中
反序列化:将文件恢复成对象
作用:
1、永久保存数据
2、传递数据
要序列化的对象对应的类以及类的属性、子类必须是可序列化的
实现序列化反序列化需要引用命名空间:
Using system.runtime.seralization.formatters.binary;
Runtime 运行时
serialization 序列化
Formatters 格式化程序,格式器
Binary 二进制的
使用实例:题==>创建一个可序列化的类(姓名,地址),然后新建一个本地文件存储信息,进行序列化和反序列化***
1.新建一个Student类,属性有学生的ID/Name/Age/Sex,定义一个父类的重写方法,实现格式化字符串:
namespace Binary
{
[Serializable]//指示一个类可以被序列化 无法继承此类
public class Student
{
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string sex;
public string Sex
{
get { return sex; }
set { sex = value; }
}
private string qq;
public string Qq
{
get { return qq; }
set { qq = value; }
}
private string homepage;
public string Homepage
{
get { return homepage; }
set { homepage = value; }
}
public Student() { }
public override string ToString()
{
return "学号:" + this.Id + "\n姓名:" + this.Name + "\n性别:" + this.Sex + "\nQQ:" + this.Qq + "\n" + this.Homepage;
}
}
}
2.Main函数中两个方法,序列化和反序列化的方法:
/// <summary>
/// 二进制序列化
/// </summary>
/// <param name="stu"></param>
public static void SerializeStudent(Student stu)
{
FileStream fs = new FileStream("d:\\studentinfo.dat", FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fs,stu);
fs.Flush();
fs.Close();
fs.Dispose();
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="filename"></param>
public static void DeSerializeStudent(string sadf)
{
FileStream fs = new FileStream(sadf, FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
BinaryFormatter b = new BinaryFormatter();
Student stu = (Student)b.Deserialize(fs);
Console.WriteLine(stu.ToString());
fs.Flush();
fs.Close();
fs.Dispose();
}
3.在Main函数中给属性赋值并实现两个自定义方法的调用,并捕获可能出现的异常:
static void Main(string[] args)
{
Student stu = new Student();
stu.Id = 20161108;
stu.Name = "张三";
stu.Sex = "男";
stu.Qq = "914455044";
stu.Homepage = "www.baidu.com";
try
{
SerializeStudent(stu);
string path = "d:\\studentinfo.dat";
DeSerializeStudent(path);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}