数据序列化处理之经验积累(1)-BinaryFormatter
以前的项目使用到了数据序列化,由此抽象出了一些辅助类来更方便的实现数据序列化处理,将一一列出共享:
二进制序列化类,此类用于类标示为Serializable,以及实现了ISerializable接口的对象的序列化:
using System;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;namespace Skyline.Tools.Serialize
{
public static class BinaryFormatSerializer
{
private static readonly BinaryFormatter InnerBinaryFormatter = new BinaryFormatter();
private readonly static MemoryStreamStack MemoryStreamStacker = new MemoryStreamStack();public static byte[] Serialize(object obj, bool compress)
{
if (obj == null)
{
return null;
}
byte[] info;
MemoryStream stream = MemoryStreamStacker.GetMemoryStream();
try
{
InnerBinaryFormatter.Serialize(stream, obj);
stream.SetLength(stream.Position);
info = stream.ToArray();
if (compress)
{
info = CompressHelper.CompressBytes(info);
}
}
finally
{
MemoryStreamStacker.ReleaseMemoryStream(stream);
}
return info;
}
public static object Deserialize(byte[] info, bool decompress)
{
if (info == null || info.Length <= 0)
{
return info;
}
object ret;
if (decompress)
{
info = CompressHelper.DeCompressBytes(info);
}
MemoryStream stream = MemoryStreamStacker.GetMemoryStream();
try
{
stream.Write(info, 0, info.Length);
stream.Position = 0L;
ret = InnerBinaryFormatter.Deserialize(stream);
}
finally
{
MemoryStreamStacker.ReleaseMemoryStream(stream);
}
return ret;
}
public static byte[] Serialize(object obj)
{
return Serialize(obj, false);
}
public static object Deserialize(byte[] info)
{
return Deserialize(info, false);
}
public static string SerializeToBase64String(object data, bool compress)
{
byte[] buffer = Serialize(data, compress);
return Convert.ToBase64String(buffer);
}public static object DeserializeFromBase64String(string baseString, bool decompress)
{
if (String.IsNullOrEmpty(baseString))
return null;byte[] buffer = Convert.FromBase64String(baseString);
return Deserialize(buffer, decompress);
}public static string SerializeToBase64String(object data)
{
return SerializeToBase64String(data, false);
}public static object DeserializeFromBase64String(string baseString)
{
return DeserializeFromBase64String(baseString, false);
}
}
}辅助类:
public class MemoryStreamStack
{
private Stack<MemoryStream> _streams = null;public MemoryStreamStack():this(100)
&
补充:综合编程 , 其他综合 ,