ArrayList的二进制序列化及反序列化实现

  • 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());   
  • }   
  • }   
  • }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值