序列化--收藏于网络一篇文章(仅供忘记时自己参考)
2008-05-22 16:21
459 查看
所谓的序列化就是是将对象转换为容易传输的格式的过程,一般情况下转化打流文件,放入内存或者IO文件中。例如,可以序列化一个对象,然后使用 HTTP 通过 Internet 在客户端和服务器之间传输该对象,或者和其它应用程序共享使用。反之,反序列化根据流重新构造对象。
.NET自带的有两种序列化对象的方式,Xml和binary的,XML 序列化不转换方法、索引器、私有字段或只读属性(只读集合除外)。要序列化对象的所有字段和属性(公共的和私有的),请使用 BinaryFormatter,而不要使用 XML 序列化(参见ms-help://MS.NETFramework.v20.chs/dv_fxserialization/html/8c63200d-db63-4a03-a93d-21641623df62.htmXML 和 SOAP 序列化)。
两者的程序处理方式基本一致,都是基于工厂模式的,下面我就只说二进制的序列化的方式:
例如我们有个对象:
[Serializable]public class ClassToSerialize{
public int id=100;
public string name="Name";
}
需要序列化该对象,必须在给该类加上Serializable的属性,然后创建一个序列化写入的流:
FileStream fileStream = new FileStream("temp.dat", FileMode.Create);
然后创建二进制格式器:
BinaryFormatter b=new BinaryFormatter();
然后是序列化:
b.Serialize(fileStream,c);
,然后关闭保存流。(可以见下面的例子)
读取一个已经被序列化的对象的时候:操作方式一样,只是
FileStream fileStream = new FileStream("temp.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
ClassToSerialize c =(ClassToSerialize)b.Deserialize(fileStream);
然后就可以读取了,完整的例子是:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class SerialTest{
public void SerializeNow(){
ClassToSerialize c=new ClassToSerialize();
FileStream fileStream = new FileStream("temp.dat", FileMode.Create);
BinaryFormatter b=new BinaryFormatter();
b.Serialize(fileStream,c);
fileStream.Close();
}
public void DeSerializeNow(){
ClassToSerialize c=new ClassToSerialize();
FileStream fileStream = new FileStream("temp.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryFormatter b=new BinaryFormatter();//SoapFormatter
c=(ClassToSerialize)b.Deserialize(fileStream);
Console.WriteLine(c.name);
fileStream.Close();
}
public static void Main(string[] s){
SerialTest st=new SerialTest();
st.SerializeNow();
st.DeSerializeNow();
}
}
[Serializable]
public class ClassToSerialize{
public int id=100;
public string name="Name";
}
这就是自带的序列化和反序列的操作,但是,很多情况下,一个对象比较大,而且很多私有的属性和方法我们不需要,例如在原型模式里面序列化的话,只需要序列Clone方法和一些属性,私有的方法无需要,还例如在读取大规模的IO的时候,读取操作完全不需要... 这时候就需要自己集成重写序列的ISerializable接口:
实现该接口需要两个注意的,一个就是构造函数,主要是为了反序列,另一个就是GetObjectData,主要是执行序列化,例如我们现在有一个Employee类需要序列化
[Serializable()] //Set this attribute to all the classes that want to serialize
public class Employee : ISerializable //derive your class from ISerializable {
public int EmpId;
public string EmpName;
[NonSerialized()]
public string NoSerialString="NoSerialString-Test";
}
,需要注意的是我这里的NoSerialString属性前面有[NonSerialized()],就是说默认并不序列化这个属性,而是使用默认值 。
首先是构造函数:
public Employee(SerializationInfo info, StreamingContext ctxt)
{
EmpId = (int)info.GetValue("EmployeeId", typeof(int));
EmpName = (String)info.GetValue("EmployeeName", typeof(string));
//NoSerialString = (String)info.GetValue("NoSerialString", typeof(string));
}
然后是序列化方法,就是当写入流的时候怎么保存的:
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
//You can use any custom name for your name-value pair. But make sure you
// read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
// then you should read the same with "EmployeeId"
info.AddValue("EmployeeId", EmpId);
info.AddValue("EmployeeName", EmpName);
}
把上面两个方法写入到Employee类,然后写个测试的程序:
public class ObjSerial{
public static void Main(String[] args){
Employee mp = new Employee();
mp.EmpId = 10;
mp.EmpName = "Omkumar";
mp.NoSerialString = "你好啊";
//序列化
Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
Console.WriteLine("Writing Employee Information");
bformatter.Serialize(stream, mp);
stream.Close();
mp = null;
//反序列
stream = File.Open("EmployeeInfo.osl", FileMode.Open);
bformatter = new BinaryFormatter();
Console.WriteLine("Reading Employee Information");
mp = (Employee)bformatter.Deserialize(stream);
stream.Close();
Console.WriteLine("Employee Id: {0}",mp.EmpId.ToString());
Console.WriteLine("Employee Name: {0}",mp.EmpName);
Console.WriteLine("Employee NoSerialString: {0}",mp.NoSerialString);
}
}
执行的结果是:
Writing Employee Information
Reading Employee Information
Employee Id: 10
Employee Name: Omkumar
Employee NoSerialString: NoSerialString-Test
看到Employee NoSerialString:属性的值没有,它保持默认值,没有序列化。
序列化很简单,但是经常用到,暂时先写到这里吧。
.NET自带的有两种序列化对象的方式,Xml和binary的,XML 序列化不转换方法、索引器、私有字段或只读属性(只读集合除外)。要序列化对象的所有字段和属性(公共的和私有的),请使用 BinaryFormatter,而不要使用 XML 序列化(参见ms-help://MS.NETFramework.v20.chs/dv_fxserialization/html/8c63200d-db63-4a03-a93d-21641623df62.htmXML 和 SOAP 序列化)。
两者的程序处理方式基本一致,都是基于工厂模式的,下面我就只说二进制的序列化的方式:
例如我们有个对象:
[Serializable]public class ClassToSerialize{
public int id=100;
public string name="Name";
}
需要序列化该对象,必须在给该类加上Serializable的属性,然后创建一个序列化写入的流:
FileStream fileStream = new FileStream("temp.dat", FileMode.Create);
然后创建二进制格式器:
BinaryFormatter b=new BinaryFormatter();
然后是序列化:
b.Serialize(fileStream,c);
,然后关闭保存流。(可以见下面的例子)
读取一个已经被序列化的对象的时候:操作方式一样,只是
FileStream fileStream = new FileStream("temp.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
ClassToSerialize c =(ClassToSerialize)b.Deserialize(fileStream);
然后就可以读取了,完整的例子是:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class SerialTest{
public void SerializeNow(){
ClassToSerialize c=new ClassToSerialize();
FileStream fileStream = new FileStream("temp.dat", FileMode.Create);
BinaryFormatter b=new BinaryFormatter();
b.Serialize(fileStream,c);
fileStream.Close();
}
public void DeSerializeNow(){
ClassToSerialize c=new ClassToSerialize();
FileStream fileStream = new FileStream("temp.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryFormatter b=new BinaryFormatter();//SoapFormatter
c=(ClassToSerialize)b.Deserialize(fileStream);
Console.WriteLine(c.name);
fileStream.Close();
}
public static void Main(string[] s){
SerialTest st=new SerialTest();
st.SerializeNow();
st.DeSerializeNow();
}
}
[Serializable]
public class ClassToSerialize{
public int id=100;
public string name="Name";
}
这就是自带的序列化和反序列的操作,但是,很多情况下,一个对象比较大,而且很多私有的属性和方法我们不需要,例如在原型模式里面序列化的话,只需要序列Clone方法和一些属性,私有的方法无需要,还例如在读取大规模的IO的时候,读取操作完全不需要... 这时候就需要自己集成重写序列的ISerializable接口:
实现该接口需要两个注意的,一个就是构造函数,主要是为了反序列,另一个就是GetObjectData,主要是执行序列化,例如我们现在有一个Employee类需要序列化
[Serializable()] //Set this attribute to all the classes that want to serialize
public class Employee : ISerializable //derive your class from ISerializable {
public int EmpId;
public string EmpName;
[NonSerialized()]
public string NoSerialString="NoSerialString-Test";
}
,需要注意的是我这里的NoSerialString属性前面有[NonSerialized()],就是说默认并不序列化这个属性,而是使用默认值 。
首先是构造函数:
public Employee(SerializationInfo info, StreamingContext ctxt)
{
EmpId = (int)info.GetValue("EmployeeId", typeof(int));
EmpName = (String)info.GetValue("EmployeeName", typeof(string));
//NoSerialString = (String)info.GetValue("NoSerialString", typeof(string));
}
然后是序列化方法,就是当写入流的时候怎么保存的:
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
//You can use any custom name for your name-value pair. But make sure you
// read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
// then you should read the same with "EmployeeId"
info.AddValue("EmployeeId", EmpId);
info.AddValue("EmployeeName", EmpName);
}
把上面两个方法写入到Employee类,然后写个测试的程序:
public class ObjSerial{
public static void Main(String[] args){
Employee mp = new Employee();
mp.EmpId = 10;
mp.EmpName = "Omkumar";
mp.NoSerialString = "你好啊";
//序列化
Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
Console.WriteLine("Writing Employee Information");
bformatter.Serialize(stream, mp);
stream.Close();
mp = null;
//反序列
stream = File.Open("EmployeeInfo.osl", FileMode.Open);
bformatter = new BinaryFormatter();
Console.WriteLine("Reading Employee Information");
mp = (Employee)bformatter.Deserialize(stream);
stream.Close();
Console.WriteLine("Employee Id: {0}",mp.EmpId.ToString());
Console.WriteLine("Employee Name: {0}",mp.EmpName);
Console.WriteLine("Employee NoSerialString: {0}",mp.NoSerialString);
}
}
执行的结果是:
Writing Employee Information
Reading Employee Information
Employee Id: 10
Employee Name: Omkumar
Employee NoSerialString: NoSerialString-Test
看到Employee NoSerialString:属性的值没有,它保持默认值,没有序列化。
序列化很简单,但是经常用到,暂时先写到这里吧。
相关文章推荐
- 关于code review 很好的一篇文章,收藏过来时刻警示自己
- 转的一篇求职经历经验的文章,很长,很有用,IT向,和自己的定位非常契合,第一时间收藏+分享。
- 《影子跟随算法》目前试着自己写一个联网双人对战的小游戏 看到一篇网络同步的文章很受启发 这里记录一下
- 收藏CSDN上一篇文章--勉励自己
- window 2008+apache2.4.4+php5.5+mysql-5.6.12+phpmyadmin4.0.4.1安装过程(参考他人文章基础上加上自己遇到的问题)
- 送给自己的一篇文章
- C语言和设计模式(工厂模式)【文章都是来自网络,只要自己吸取了就是自己的】
- C语言和设计模式(建造者模式) 【文章都是来自网络,只要自己吸取了就是自己的】
- C语言和设计模式(命令模式)【文章都是来自网络,只要自己吸取了就是自己的】
- jq封装ajax的一些方法(仅供自己参考)
- 关于GridBagLayout网络上一篇很好的文章
- 搜集论坛SQL问题集合.仅供自己和有兴趣的朋友参考。不做其他用途
- 签了工作之后才发现,自己太草率了.....我看过的关于职业规划最好最全面的一篇文章
- 编写多文件,多目录makefile(借鉴网上的一篇文章来自己练手)
- 北大牛人唐翔(贴一篇文章激励一下自己)
- 前面的总结不太好,找了一篇总结的挺好的,仅供学习参考
- 网络编程----心得体会(一篇解决你大部分疑惑的文章)
- 哈哈。。发现自己每个月至少都有发一篇文章
- 转载自己之前一篇写刘备的文章:折而不挠,当为世所敬仰的我大汉皇叔!
- 签了工作之后才发现,自己太草率了.....我看过的关于职业规划最好最全面的一篇文章