ArrayList的二进制序列化及反序列化实现
来源:互联网 发布:mac jenkins 安装教程 编辑:程序博客网 时间:2024/05/16 18:41
using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.Data; using System.Data.SqlClient; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace ConsoleApplication5 { class Program { private static BinaryFormatter Transfer = new BinaryFormatter(); static void Main(string[] args) { Test test = new Test(10); ArrayList array = new ArrayList(); array.Add(test); byte[] buffer = ChangeObjectToByte(array); ArrayList array2 = new ArrayList(); array2 = (ArrayList)ChangeByteToObject(buffer); Test test2 = (Test)array2[0]; test2.PrintKey(); Console.ReadLine(); } private static object ChangeByteToObject(byte[] buffer) { try { MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, true, true); object obj = Transfer.Deserialize(ms); return obj; } catch (Exception err) { return null; } } private static byte[] ChangeObjectToByte(object obj) { MemoryStream ms = new MemoryStream(); Transfer.Serialize(ms, obj); byte[] buffer = ms.GetBuffer(); return buffer; } } [Serializable] public class Test { private int _key; public Test(int Key) { this._key = Key; } public void PrintKey() { Console.WriteLine(_key.ToString()); } } }