C#序列化与反序列化
时间:2011-05-25 来源:zhxhdean
概念:
序列化:持久化一个对象的状态到流的过程。
反序列化:被持久化的数据到对象的过程。
使用这技术,用最小花费来保存海量的数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;
namespace 序列化反序列化
{
class Program
{
static void Main(string[] args)
{
Person p = new Person(2, "zhxhdean", 25);
/**********************使用BinaryFormatter序列化和反序列化******************************/
//需要引用using System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter bf = new BinaryFormatter();
using (Stream stream = new FileStream("person.dat", FileMode.Create, FileAccess.Write, FileShare.None))
{
//序列化.将对象以二进制保存到person.dat文件
bf.Serialize(stream, p);
}
using (Stream stream = File.OpenRead("person.dat"))
{
//反序列化
Person p2 = (Person)bf.Deserialize(stream);
Console.WriteLine("Person name is {0}", p2.Name);
}
/***********************使用SoapFormatter序列化和反序列化**********************************/
//需要using System.Runtime.Serialization.Formatters.Soap;
SoapFormatter sf = new SoapFormatter();
using (Stream stream = new FileStream("person.soap", FileMode.Create, FileAccess.Write, FileShare.None))
{
//序列化.将对象以二进制保存到person.dat文件
sf.Serialize(stream, p);
}
using (Stream stream = File.OpenRead("person.soap"))
{
//反序列化
Person p2 = (Person)sf.Deserialize(stream);
Console.WriteLine("Person name is {0}", p2.Name);
}
/************************使用XmlSerializer序列化和反序列化*******************************/
//需要using System.Xml.Serialization;
//注意:XmlSerializer只能序列化公开类型,这些类型中的字段数据的公共块或拥有公共属性的私有数据可以被序列
化。如Person类不是Public,则不能被序列化
XmlSerializer xs = new XmlSerializer(typeof(Person));
using (Stream stream = new FileStream("person.xml", FileMode.Create, FileAccess.Write, FileShare.None))
{
//序列化.将对象以二进制保存到person.dat文件
xs.Serialize(stream, p);
}
using (Stream stream = File.OpenRead("person.xml"))
{
//反序列化
Person p2 = (Person)xs.Deserialize(stream);
Console.WriteLine("Person name is {0}", p2.Name);
}
}
}
[Serializable]
public class Person
{
//如果自动不需要序列化就标示NonSerialized
[NonSerialized]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Person()
{
}
public Person(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
}
}
}
相关阅读 更多 +