• 对象的序列化存入数据库,与反序列化


    开发过程中遇到一个问题,我想到的解决方法是将一个dictionary字典如何存如数据库,读出来的时候还是这个字典

    然后接触到对象的序列化与反序列化。开始打算序列化成为xml的形式,因为sqlserver中有xml字段,可是dictionary无法进行序列化。那么就只能序列化成为二进制流存到数据库的image字段中
    通过linqtosql回来的字段查看,其实image是binary形式的。

    首先设计数据库的要存储的对象的字段为image类型

    然后写一个序列化的类
    例如:

     1 [Serializable()]
    2 public class PermissionModel
    3 {
    4 public Dictionary Dict = new Dictionary();
    5 public void Add(string key,string value)
    6 {
    7 Dict.Add(key, value);
    8 }
    9 public void Clear()
    10 {
    11 Dict.Clear();
    12 }
    13 public void Remove(string key)
    14 {
    15 Dict.Remove(key);
    16 }
    17 }

    之后就可以正常的像这个对象的字典中插入数据了。

    1 PermissionModel model=new PermissionModel();
    2 model.Add("0", "1");
    3 ......
    4 model.Add("N", "N");

    通过下面的方法,可以将该对象序列化成为二进制流。

    1 System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    2 System.IO.Stream stream = new System.IO.MemoryStream();
    3 formatter.Serialize(stream, model);
    4 stream.Flush();
    5 stream.Position = 0;
    6 byte[] bytes = new byte[stream.Length];
    7 stream.Read(bytes, 0, Convert.ToInt32(stream.Length));
    8 stream.Close();

    直接将bytes给数据库中的字段进行保存就好了。

    下面进行反序列化。

    1 System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    2 tPermissionModel perModel = 查询方法;
    3 byte[] bytes = null;
    4 bytes = (byte[])perModel.ModelObject.ToArray();
    5 System.IO.Stream stream = new System.IO.MemoryStream(bytes);
    6 PermissionModel obj = (PermissionModel)formatter.Deserialize(stream);
    7 stream.Close();

    通过上面这个方法查询回来的并进行反序列化后的obj就是之前存入数据库中的对象。

    dictionary的遍历方法。

    1 foreach (KeyValuePair entry in obj.Dict)
    2 {
    3 //enery.Key and entry.Value
    4 }

    只是不知道我这样的写法是不是好的方法呢。因为没时间去验证效率什么的。



    http://luacloud.com/2010/%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%BA%8F%E5%88%97%E5%8C%96%E5%AD%98%E5%85%A5%E6%95%B0%E6%8D%AE%E5%BA%93%EF%BC%8C%E4%B8%8E%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96.html

  • 相关阅读:
    php详解和优化
    接口
    抽象类
    对象转型
    面向对象2
    Super关键字
    Object类介绍
    有效处理java异常的三个原则
    this关键字
    equals方法
  • 原文地址:https://www.cnblogs.com/luacloud/p/2265758.html
Copyright © 2020-2023  润新知