using System;标签:二进制,ArrayList,System,buffer,new,Test,using,序列化 From: https://blog.51cto.com/kenkao/5989783
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, true, true);
//将流反序列化为对象
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());
}
}
}