欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

C# 对象持久化图文代码详解

程序员文章站 2022-04-12 15:42:20
...
本文介绍的是除数据库之外的几种对象持久化方式。具有很好的参考价值,下面跟着小编一起来看下吧

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

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

具体如下:

  1. 保存成文本:即将内存对象以字节流的方式保存到文本中。

  2. 序列化成Xml:即将对象以Xml的格式存储。

  3. 序列化成Json:即将对象序列化成Json对象,然后存储。

  4. 序列化成二进制:即将对象序列化成二进制字节流保存到文件中。

涉及知识点:

  1. 序列化与反序列化

  2. 文件流的读写

  3. ListView显示复选框,并横向排列

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

C# 对象持久化图文代码详解

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

/// <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);
  }

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

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

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

以上就是C# 对象持久化图文代码详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!

相关标签: C#,对象持久化