关于C#序列化结果的长度获取
??? 關于C#序列化的文章真的是好多,但是內容大致一樣,主要分四類:
??? 最近的一個項目需要使用Socket進行通信,所以必然涉及序列化的問題。使用BinarySerialize序列化之后發現無論如何獲取不了序列化后的實際長度,代碼如下
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary;namespace Serialize {public class BinarySerialize{byte[] buffer=new byte[1024];public void Serialize(Book book){using (MemoryStream fs = new MemoryStream(buffer, 0,1024)){BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(fs, book);}}public Book DeSerialize(){Book book;using (MemoryStream fs = new MemoryStream(buffer,0,1024)){BinaryFormatter formatter = new BinaryFormatter();book = (Book)formatter.Deserialize(fs);}return book;}} }??? 通過MemoryStream獲取長度,永遠是1024。后來試了好久發現其實只需要改一點點地方就可以了,改正后的代碼如下,順便做了點通用性擴展:
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary;namespace Serialize {public class MemoryBinarySerialize{public static byte[] Serialize(object obj){MemoryStream fs = new MemoryStream();BinaryFormatter formatter = new BinaryFormatter();formatter.Serialize(fs, obj);return fs.GetBuffer();}public static object DeSerialize(byte[] data){MemoryStream fs = new MemoryStream(data);BinaryFormatter formatter = new BinaryFormatter();object obj= formatter.Deserialize(fs);return obj;}} }??? 參考文獻:
??? C#序列化技術詳解(轉):http://www.cnblogs.com/ejiyuan/archive/2009/01/21/1379256.html
??? 序列化和反序列化(Socket中傳遞Object):http://dev.firnow.com/course/4_webprogram/asp.net/netjs/20081011/150063.html
??? C#中JSON的序列化和反序列化:http://www.dotnetdev.cn/2010/01/c%E4%B8%AD%E7%9A%84json%E7%9A%84%E5%BA%8F%E5%88%97%E5%8C%96%E5%92%8C%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96/
轉載于:https://www.cnblogs.com/sdqxcxh/archive/2011/01/19/1939101.html
總結
以上是生活随笔為你收集整理的关于C#序列化结果的长度获取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】温州的南拳
- 下一篇: 22(2)序列化以及反序列化