因为需要把复杂事物组合放进数据库,因此采用了将类转成二进制,直接插入到一个字段
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;
        }

    }

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-05-30
  • 2021-12-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-28
  • 2021-11-02
  • 2022-12-23
  • 2022-12-23
  • 2021-09-04
  • 2022-12-23
相关资源
相似解决方案