1.序列化 反序列化
C#中如果需要:將一個結構很復雜的類的對象存儲起來,或者通過網路傳輸到遠程的客戶端程序中去,這時就需要用到序列化,反序列化(Serialization & Deserialization)
2.BinaryFormattter
.NET中串行有三種,BinaryFormatter, SoapFormatter和xmlSerializer.
其中BinaryFormattter最簡單,它是直接用二進制方式把對象 (Object)進行串行或反串,他的優點是速度快,可以串行PRivate或者protected的member, 在不同版本的。NET中都兼容,可以看作是。NET自己的本命方法,當然缺點也就隨之而來了,離開了。NET它就活不了,所以不能在其他平臺或跨網路上進 行。
3.序列化
BinaryFormatter ser = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
ser.Serialize(ms, DS);
byte[] buffer = ms.ToArray();
MemoryStream :創建其支持存儲區為內存的流
4.反序列化
//反序列化:將byte[]型的數據,放到Stream中,BinaryFormatter將流中的數據反序列化成對象
MemoryStream ms = new MemoryStream(bytes);
BinaryFormatter ser = new BinaryFormatter();
DataSetSurrogate dss = ser.Deserialize(ms) asDataSetSurrogate;
5.小結
進行序列化,反序列化,利用到的都是BinaryFormate,都得借普通流MemoryStream,不同的是:
序列化時,將對象序列化后放到MemoryStream,而反序列化時,將MemoryStream中的byte[]數據,反序列成對象
新聞熱點
疑難解答