zoukankan      html  css  js  c++  java
  • 序列化类,将类转为二进制

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

        }

  • 相关阅读:
    vue样式的动态绑定
    vue表单选项框
    vue简单逻辑判断
    vue的选项卡功能
    简单vue的监听属性(单位换算)
    简单的Vue计算属性
    vue.js 入门
    head元素的内容
    HTML实体
    CSS元素的盒类型
  • 原文地址:https://www.cnblogs.com/soonfly/p/1550830.html
Copyright © 2011-2022 走看看