技术开发 频道

如何以对象的形式存储数据


【IT168技术文档】

  .NET Framework在System.Runtime.Serialization和System.Runtime.Serialization.Formatters命名空间中提供了串行化对象的基础架构,这两个命名空间中的一些类实现了这个基础架构。Framework中有两个可用的实现方式:

  ● System.Runtime.Serialization.Formatters.Binary:这个命名空间包含了BinaryFormatter类,它能把对象串行化为二进制数据,把二进制数据串行化为对象。

  ● System.Runtime.Serialization.Formatters.Soap:这个命名空间包含了SoapFormatter类,它能把对象串行化为SOAP格式的XML数据,把SOAP格式的XML数据串行化为对象。

  三个步骤:

  1:创建对象
using System; using System.Collections.Generic; using System.Text; namespace类序列化测试 { ///<summary> ///测试序列化 ///</summary> [Serializable] 一定要加上这个,指示类支持序列化 public class ClassTest { private string _strUserCode; private string _strUserName; ///<summary> ///用户代码 ///</summary> public string UserCode { get { return this._strUserCode; } set { this._strUserCode = value; } } ///<summary> ///用户名称 ///</summary> public string UserName { get { return this._strUserName; } set { this._strUserName = value; } } ///<summary> ///设置用户信息 ///</summary> ///<param name="userCode">用户代码</param> ///<param name="userName">用户名称和</param> ///<returns></returns> public void SetUserInfo(string userCode, string userName) { this._strUserCode = userCode; this._strUserName = userName; } } }

  2:序列化对象
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Xml.Serialization; using System.IO;
2.1 二进制方式 ClassTest Ct = new ClassTest(); Ct.SetUserInfo(textBox1.Text, textBox2.Text); IFormatter Fm = new BinaryFormatter(); Stream stream = new FileStream(@"E:"测试"类序列化"类序列化测试"类序列化测试"myfile.bin", FileMode.Create, FileAccess.ReadWrite, FileShare.None); Fm.Serialize(stream, Ct); stream.Close(); 2.2 XML 方式 ClassTest Ct = new ClassTest(); Ct.SetUserInfo(textBox1.Text, textBox2.Text); XmlSerializer Xs = new XmlSerializer(typeof(ClassTest)); StreamWriter myWriter = new StreamWriter(@"E:"测试"类序列化"类序列化测试"类序列化测试"myfile.xml"); Xs.Serialize(myWriter, Ct); myWriter.Close();
  3:反序列化得到对象
IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(@"E:"测试"类序列化"类序列化测试"类序列化测试"myfile.bin", FileMode.Open, FileAccess.Read, FileShare.Read); ClassTest obj = (ClassTest)formatter.Deserialize(stream); stream.Close();
  这两种方式,二进制方式,文件小速度快,但不易阅读;XML 方式相对文件大一点,速度稍慢。但可读性较好
0
相关文章