Detailed explanation of C# object persistence graphic code
本文介绍的是除数据库之外的几种对象持久化方式。具有很好的参考价值,下面跟着小编一起来看下吧
对象持久化是指将内存中的对象保存到可永久保存的存储设备中(如磁盘)的一种技术。
本文介绍的是除数据库之外的几种对象持久化方式。
具体如下:
保存成文本:即将内存对象以字节流的方式保存到文本中。
序列化成Xml:即将对象以Xml的格式存储。
序列化成Json:即将对象序列化成Json对象,然后存储。
序列化成二进制:即将对象序列化成二进制字节流保存到文件中。
涉及知识点:
序列化与反序列化
文件流的读写
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); }
备注:其实对象持久化和对象序列化是两个不同的概念。两者有关联却不同。
对象持久化:是使对象可以保存到实体存储介质中,在对象生命周期结束后可以再现。
对象序列化:是将对象或者数据结构转化成特定的格式,使其可在网络中传输,或者可存储在内存或者文件中。
以上就是C# 对象持久化图文代码详解的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to the Access Modifiers in C#. We have discussed the Introduction Types of Access Modifiers in C# along with examples and outputs.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to C# StringReader. Here we discuss a brief overview on C# StringReader and its working along with different Examples and Code.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to C# StringWriter. Here we discuss a brief overview on C# StringWriter Class and its working along with different Examples and Codes.
