您的位置:首页 > 编程语言 > C#

C#对象序列化详解

2013-12-08 17:30 357 查看
             C#中的序列化主要是通过一个格式化工具获取某个自定义类型对象中的所有数据成员并写入传入的一个文件流中,或者从文件流对象中

              解析出某个自定义类型对象中的所有数据成员并赋值到一个该类型对象中。从而实现了用二进制流来处理对象的存储问题。

              其中C#里的格式化工具可以分为BinaryFormatter(二进制格式化工具)、SoapFormatter(XML格式化工具)这儿先说BinaryFormatter

              再去说SoapFormatter

              在序列化的过程中首先要用[Serializable()]来标志某个类是可以被序列化的,在利用BinaryFormatter该二进制格式化工具来处理对象。

              当然BinaryFormatter也是可以一次序列化多个对象到文件中,和一次从文件中反序列化多个对象出来的,
             --------------------YYC

            openFileDialog1.Filter = "文本文件(*.txt)|*.txt";

            if(openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)

            {

              string path = openFileDialog1.FileName;

              TestC tc = new TestC();

              tc.A = 1;

              tc.B = 2.2;

              tc.STR = "YYC";

              //首先创建流对象

              FileStream fsl = File.Open(path,FileMode.Open,FileAccess.ReadWrite);

              //创建序列化的格式化工具

              BinaryFormatter bf = new BinaryFormatter();

              //序列化

              bf.Serialize(fsl, tc);

              fsl.Close();

              fsl = File.Open(path,FileMode.Open,FileAccess.ReadWrite);

              TestC tb = new TestC();

              //反序列化

              tb = (TestC)bf.Deserialize(fsl);

              fsl.Close();

            //  MessageBox.Show(tb.A.ToString()+"   "+tb.B.ToString()+"    "+tb.STR);

              //SoapFormatter

             使用XML格式化工具时的使用方法和BinaryFormatter一样,都是需要传入自定义类型对象和文件流对象。

              其唯一的区别就是使用这种方式存储时得到的文件里的内容也是XML格式的文件。

              例如用以下方式得到的文件内容为:

                  <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

                  <SOAP-ENV:Body>

                  <a1:TestC id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/PraccticeInDetail/PraccticeInDetail%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">

                  <a>1</a>

                  <b>2.2</b>

                  <str id="ref-3">YYC</str>

                  </a1:TestC>

                  </SOAP-ENV:Body>

                  </SOAP-ENV:Envelope>

                

              fsl = File.Open(path, FileMode.Open, FileAccess.ReadWrite);

              SoapFormatter sf = new SoapFormatter();

              sf.Serialize(fsl,tc);

              fsl.Close();

              fsl = File.Open(path, FileMode.Open, FileAccess.ReadWrite);

              tb = (TestC)sf.Deserialize(fsl);

              fsl.Close();

              MessageBox.Show(tb.A.ToString() + "   " + tb.B.ToString() + "    " + tb.STR);

              
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息