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(); //应该会打印出"10",证明自己其实是第一个test那个对象   
  •   
  • Console.ReadLine();   
  • }   
  •   
  • /// <summary>   
  • /// 反序列化   
  • /// </summary>   
  • /// <param name="buffer">二进制流</param>   
  • private static object ChangeByteToObject(byte[] buffer)   
  • {   
  • try   
  • {   
  • MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, truetrue);   
  • //将流反序列化为对象   
  • object obj = Transfer.Deserialize(ms);   
  •   
  • return obj;   
  • }   
  • catch (Exception err)   
  • {   
  • return null;   
  • }   
  • }   
  •   
  • /// <summary>   
  • /// 序列化   
  • /// </summary>   
  • /// <param name="msg">要序列化的对象</param>   
  • /// <returns>转化成的byte</returns>   
  • 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());   
  • }   
  • }   
  • }  
  • 原创粉丝点击