因为需要把复杂事物组合放进数据库,因此采用了将类转成二进制,直接插入到一个字段
public static class Serializer
{
public static byte[] ToBinary<T>(this T o) where T : class, new()
{
byte[] bytes = null;
DataContractSerializer dc = new DataContractSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
//formatter.Serialize(ms, value);
dc.WriteObject(ms, o);
ms.Seek(0, 0);
bytes = ms.ToArray();
}
return bytes;
}
public static TResult FromBinary<TResult>(this TResult input, byte[] bits) where TResult : class, new()
{
TResult result = default(TResult);
DataContractSerializer dc = new DataContractSerializer(typeof(TResult));
//IFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(bits))
{
result = (TResult)dc.ReadObject(ms);
}
return result;
}
}
如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛