c#如何使用MemoryStream和BinaryFormatter进行对象的序列化和返序列化
1 下面是我写的一个序列化的类
public static class ObjSerialize
{
/// <summary>
/// 将对象数组obj序列化,内存中的缓冲区的数据序列化
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static byte[] Serialize(object obj)
{
byte[] arr = null;
if (obj!=null)
{
//MemoryStream类用于向内存而不是磁盘读写数据
using (MemoryStream ms=new MemoryStream())
{
//序列化操作,把内存中的东西写到硬盘中
BinaryFormatter fomatter = new BinaryFormatter();
fomatter.Serialize(ms, obj);
ms.Flush();
arr = ms.ToArray();
}
}
return arr;
}
public static object Deserialize(byte[] arr)
{
object obj = null;
using (MemoryStream ms=new MemoryStream())
{
ms.Write(arr, 0, arr.Length);
ms.Flush();
ms.Position = 0;
BinaryFormatter formatter = new BinaryFormatter();
obj= formatter.Deserialize(ms);
}
return obj;
}
}
2 测试这个类
我自己新建了一个student的对象,他只有id和name两个属性
控制台测试代码这里需要吧student类标记为serializable
Student stu = new Student()
{
ID = 1,
Name = "王宝强"
};
byte[] arr= ObjSerialize.Serialize(stu);
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
结果如下:
反序列化的测试代码和结果如下
Student ss= (Student)ObjSerialize.Deserialize(arr);
Console.WriteLine("{0}----{1}",ss.ID,ss.Name);
转载于:https://www.cnblogs.com/mibing/p/5808078.html
标签:arr,obj,MemoryStream,c#,BinaryFormatter,ms,序列化 From: https://www.cnblogs.com/kelelipeng/p/17148119.html