.net序列化与反序列化
二进制序列化
首先引用
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
自定义类:
[Serializable]
public class person
{
private int Age;public int Age1
{
get { return Age; }
set { Age = value; }
}
private string Name;public string Name1
{
get { return Name; }
set { Name = value; }
}public person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
代码:
person p = new person("高", 20);BinaryFormatter formatter = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
formatter.Serialize(ms, p); //二进制序列化
byte[] content = ms.ToArray();
Response.Write(BitConverter.ToString(content)); //把字符数组以字符串形式输出
MemoryStream ms2 = new MemoryStream(content);
person p2 = formatter.Deserialize(ms2) as person; //二进制反序列化
Response.Write(p2.Age1);
ObjectStateFormatter进行序列化
ObjectStateFormatter osf = new ObjectStateFormatter();
string base64 = osf.Serialize(p);
Response.Write(base64);person p3= osf.Deserialize(base64) as person;