序列化是将一个对象转换成字节流以达到将其长期保存在内存、数据库或文件中的处理过程。它的主要目的是保存对象的状态以便以后需要的时候使用。与其相反的过程叫做反序列化。
序列化一个对象 为了序列化一个对象,我们需要一个被序列化的对象,一个容纳被序列化了的对象的(字节)流和一个格式化器。进行序列化之前我们先看看System.Runtime.Serialization名字空间。ISerializable接口允许我们使任何类成为可序列化的类。
如果我们给自己写的类标识[Serializable]特性,我们就能将这些类序列化。除非类的成员标记了[NonSerializable],序列化会将类中的所有成员都序列化。
序列化的类型
二进制(流)序列化 SOAP序列化(使用IXmlSerializable) XML序列化 通常大部分都是使用的XML序列化,所以介绍一下使用XML序列化.
Student类
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace XmlSerializers { [Serializable] public class Student { private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
private string hoddy;
public string Hoddy
{
get { return hoddy; }
set { hoddy = value; }
}
public Student()
{
}
public Student(string name,int age,string hoddy)
{
= name;
this.Age = age;
this.Hoddy = hoddy;
}
public void SayHi()
{
string mess = string.Format("我是{0},年龄有{1},爱好是{2}", Name, Age, Hoddy);
Console.WriteLine(mess);
}
}
}
Program
using System; using System.Collections.Generic; using System.Linq; using System.Text;
using System.IO; using System.Xml.Serialization; using System.Xml;
namespace XmlSerializers { [Serializable] class Program {
static List<Student> students = new List<Student>();
static void Main(string[] args)
{
//添加学生
InitStudent();
//序列化
Serialize();
//反序列化
Deserialize();
Console.ReadLine();
}
public static void InitStudent()
{
Student scoficedld = new Student("scofield", 28, "哈哈");
Student su = new Student("程沐喆", 34, "写博客");
Student zhang = new Student("张婧", 21, "唱歌");
Student huang = new Student("黄飞鸿", 25, "打架");
Student ding = new Student("丁俊晖", 30, "打斯诺克");
Student sullivan = new Student("OSullivan", 33, "打147");
Student Jay = new Student("周杰", 21, "耍双节棍");
students.Add(scoficedld);
students.Add(su);
students.Add(zhang);
students.Add(huang);
students.Add(ding);
students.Add(sullivan);
students.Add(Jay);
}
public static void Serialize()
{
FileStream fs = new FileStream("Serialize.xml", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
xs.Serialize(fs, students);
fs.Close();
}
public static void Deserialize()
{
FileStream fs = new FileStream("Serialize.xml", FileMode.Open);
XmlSerializer xs = new XmlSerializer(typeof(List<Student>));
List<Student> lists = xs.Deserialize(fs) as List<Student>;
if (lists != null)
{
for (int i = 0; i < lists.Count; i++)
{
lists[i].SayHi();
}
}
fs.Close();
}
}
}