C# 对象持久化详解

对象持久化是指将内存中的对象保存到可永久保存的存储设备中(如磁盘)的一种技术。

本文介绍的是除数据库之外的几种对象持久化方式。

具体如下:

  1. 保存成文本:即将内存对象以字节流的方式保存到文本中。
  2. 序列化成Xml:即将对象以Xml的格式存储。
  3. 序列化成Json:即将对象序列化成Json对象,然后存储。
  4. 序列化成二进制:即将对象序列化成二进制字节流保存到文件中。

涉及知识点:

  1. 序列化与反序列化
  2. 文件流的读写
  3. ListView显示复选框,并横向排列

如下图所示【主要功能是将用户输入的信息保存成各种格式,并从各个文档中进行读取出来】:

保存和读取文本文档代码如下:

/// <summary>
  /// 保存成文本
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnSaveTxt_Click(object sender, EventArgs e)
  {
   Dictionary<string, string> dicInfos = GetDictionaryInfos();
   string filePath = "objPerson.txt";
   //采用using关键字,会自动释放
   using (FileStream fs = new FileStream(filePath, FileMode.Create))
   {
    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
    {
     foreach (var keyPair in dicInfos)
     {
      sw.WriteLine(string.Format("{0}={1}", keyPair.Key, keyPair.Value));
     }
    }
   }
  }
  /// <summary>
  /// 从文本中读取
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnReadTxt_Click(object sender, EventArgs e)
  {
   string filePath = "objPerson.txt";
   Dictionary<string, string> dic = new Dictionary<string, string>();
   //采用using关键字,会自动释放
   using (FileStream fs = new FileStream(filePath, FileMode.Open))
   {
    using (StreamReader sw = new StreamReader(fs, Encoding.Default))
    {
     while (!sw.EndOfStream) {
      string lineInfo = sw.ReadLine();
      dic.Add(lineInfo.Split('=')[0], lineInfo.Split('=')[1]);
     }
    }
   }
   this.txtName.Text = dic["Name"];
   this.dtBirthday.Text = dic["Birthday"];
   if (dic["Gender"] == this.rbBoy.Text)
   {
    this.rbBoy.Checked = true;
   }
   else {
    this.rbGirl.Checked = true;
   }
   string[] loves = dic["Love"].Split('|');
   foreach (var love in loves)
   {
    foreach (var item in this.lsvLove.Items)
    {
     ListViewItem li = item as ListViewItem;
     if (li.Text == love)
     {
      li.Checked = true;
     }
    }
   }
  }

保存和读取Xml文档代码如下:

/// <summary>
  /// 保存成Xml
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnSaveXml_Click(object sender, EventArgs e)
  {
   Person p = GetPersonInfos();
   string filePath = "objPerson.xml";
   using (FileStream fs = new FileStream(filePath, FileMode.Create))
   {
    XmlSerializer serializer = new XmlSerializer(typeof(Person));
    serializer.Serialize(fs, p);
   }
  }
  /// <summary>
  /// 从Xml中读取
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnReadXml_Click(object sender, EventArgs e)
  {
   string filePath = "objPerson.xml";
   Person p;
   using (FileStream fs = new FileStream(filePath, FileMode.Open))
   {
    XmlSerializer serializer = new XmlSerializer(typeof(Person));
    object obj= serializer.Deserialize(fs);
    p = obj as Person;
   }
   SetPersonInfos(p);
  }

保存和读取Json文档如下:

/// <summary>
  /// 保存成Json
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnSaveJson_Click(object sender, EventArgs e)
  {
   Person p = GetPersonInfos();
   JavaScriptSerializer jserializer = new JavaScriptSerializer();
   string strJson = jserializer.Serialize(p);
   string strRegex = @"\\/Date\((\d+)\)\\/";
   MatchEvaluator evaluator = new MatchEvaluator(ConvertJsonDateToDateString);

   //对时间进行处理,需要引用System.Text.RegularExpressions;命名空间
   Regex reg = new Regex(strRegex);
   strJson = reg.Replace(strJson, evaluator);
   string filePath = "objPerson.json";
   using (FileStream fs = new FileStream(filePath, FileMode.Create))
   {
    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
    {
     sw.Write(strJson);
    }
   }
  }
  /// <summary>
  /// 从Json中读取
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnReadJson_Click(object sender, EventArgs e)
  {
   JavaScriptSerializer jserializer = new JavaScriptSerializer();
   string filePath = "objPerson.json";
   Person p;
   using (FileStream fs = new FileStream(filePath, FileMode.Open))
   {
    using (StreamReader sw = new StreamReader(fs, Encoding.Default))
    {
     string strJson = sw.ReadToEnd();
     string strRegex = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
     MatchEvaluator evaluator = new MatchEvaluator(ConvertDateStringToJsonDate); //对时间进行处理
     Regex reg = new Regex(strRegex);
     strJson = reg.Replace(strJson, evaluator);
     p = jserializer.Deserialize<Person>(strJson);
    }
   }
   SetPersonInfos(p);
  }

保存和读取Bin文档如下:

/// <summary>
  /// 保存成二进制文件
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnSaveBin_Click(object sender, EventArgs e)
  {
   Person p = GetPersonInfos();
   string filePath = "objPerson.bin";
   using (FileStream fs = new FileStream(filePath, FileMode.Create)) {
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(fs, p);
   }
  }
  /// <summary>
  /// 读取二进制文件
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnReadBin_Click(object sender, EventArgs e)
  {
   string filePath = "objPerson.bin";
   Person p;
   using (FileStream fs = new FileStream(filePath, FileMode.Open))
   {
    BinaryFormatter bf = new BinaryFormatter();
    p= bf.Deserialize(fs) as Person;
   }
   SetPersonInfos(p);
  }

备注:其实对象持久化和对象序列化是两个不同的概念。两者有关联却不同。

对象持久化:是使对象可以保存到实体存储介质中,在对象生命周期结束后可以再现。

对象序列化:是将对象或者数据结构转化成特定的格式,使其可在网络中传输,或者可存储在内存或者文件中。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持呐喊教程!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。