1.序列化和反序列化
对象序列化是将对象(比如Person对象)转换为二进制数据,反序列化是将二进制数据还原为对象,对象是稍纵即逝的,不仅程序重启,操作系统重启会造成对象的消失,就是推出函数范围等都可能造成对象的小时,序列化或者反序列化就是为了保持对象的持久化,就像用DV录像(序列化)和用播放器(反序列化)一样。
2.BinaryFormatter类有2个方法:
(1)void Serialize(Stream stream,object graph)对象graph序列化到stream中
(2)object Deserialize(Stream stream) 将对象从stream中反序列化,返回值为序列化得到的对象。
3.注意:不是所有的对象都能序列化,只有可序列化的对象才能序列化,所以必须在类声明上添加[Serializable]
4.例子:
namespace text
{
class Program
{
static void Main(string[] args)
{
List<Person> personList = new List<Person> { new Person("zhao", 1),new Person("zhang",2) };
//写入
using (FileStream fsWrite = new FileStream(@"C:\Users\asus\Desktop\111.txt", FileMode.Create))
{
//可以将数据转化为二进制数据
BinaryFormatter binaryFormatter = new BinaryFormatter();
//使用binaryFormatter对象将personList集合转换为二进制数据,以流的形式写入到指定文件
binaryFormatter.Serialize(fsWrite, personList);
}
//读出
using (FileStream fsRead = new FileStream(@"C:\Users\asus\Desktop\111.txt", FileMode.Open))
{
{
class Program
{
static void Main(string[] args)
{
List<Person> personList = new List<Person> { new Person("zhao", 1),new Person("zhang",2) };
//写入
using (FileStream fsWrite = new FileStream(@"C:\Users\asus\Desktop\111.txt", FileMode.Create))
{
//可以将数据转化为二进制数据
BinaryFormatter binaryFormatter = new BinaryFormatter();
//使用binaryFormatter对象将personList集合转换为二进制数据,以流的形式写入到指定文件
binaryFormatter.Serialize(fsWrite, personList);
}
//读出
using (FileStream fsRead = new FileStream(@"C:\Users\asus\Desktop\111.txt", FileMode.Open))
{
personList.Clear();
BinaryFormatter binaryFormatter = new BinaryFormatter();
personList = (List<Person>) binaryFormatter.Deserialize(fsRead);
foreach (Person tempPerson in personList)
{
Console.WriteLine(string.Format("姓名:{0},年龄:{1}", tempPerson.Name, tempPerson.Age));
}
}
Console.ReadKey();
}
}
[Serializable]
public class Person
{
private string name;
private int age;
public Person(string theName, int theAge)
{
Name = theName;
Age = theAge;
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
}
BinaryFormatter binaryFormatter = new BinaryFormatter();
personList = (List<Person>) binaryFormatter.Deserialize(fsRead);
foreach (Person tempPerson in personList)
{
Console.WriteLine(string.Format("姓名:{0},年龄:{1}", tempPerson.Name, tempPerson.Age));
}
}
Console.ReadKey();
}
}
[Serializable]
public class Person
{
private string name;
private int age;
public Person(string theName, int theAge)
{
Name = theName;
Age = theAge;
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
}
}