c# 简单序列化
序列化:是將對象狀態轉換為可保持或傳輸的格式的過程,原因有兩個,第一是想永久的保存這些數據,以便將來可以重建這些數據。第二是想把數據從一個應用程序域發送到另外一個應用程序域中去。
反序列化:就是把存儲介質中的數據重新構建為對象的一個過程。
?
首先創建一個類MyObject,如以下代碼
MyObjectusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SerializeTest
{
??? [Serializable]
??? public class MyObject
??? {
??????? public int n1 = 0;
??????? public int n2 = 0;
??????? public string str = null;
??? }
}
再創建一個類用來寫序列化和反序列化方法以下代碼包含2種方式二進制和xml方式。
SerializableCodeusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;//用二進制方式進行序列化要導入的命名空間
using System.Xml.Serialization; //用xml方式進行序列化要導入的命名空間
namespace SerializeTest
{
??? public class Serializable
??? {
??????? public void SeriaByBinary()
??????? {
??????????? MyObject obj = new MyObject();
??????????? obj.n1 = 1;
??????????? obj.n2 = 24;
??????????? obj.str = "binary is good";
??????????? IFormatter formatter = new BinaryFormatter();
??????????? Stream stream=new FileStream("c:\\Myfile.bin",FileMode.Create,FileAccess.Write,FileShare.None);
??????????? formatter.Serialize(stream,obj);
??????????? stream.Close();
??????? }
??????? public MyObject DSeriaByBinary()
??????? {
??????????? IFormatter formatter = new BinaryFormatter();
??????????? Stream stream = new FileStream("c:\\Myfile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
??????????? MyObject obj=(MyObject)formatter.Deserialize(stream);
??????????? stream.Close();
??????????? return obj;
??????? }
??????? public void SeriaByXml()
??????? {
??????????? MyObject obj = new MyObject();
??????????? obj.n1 = 1111;
??????????? obj.n2 = 2222;
??????????? obj.str = "xml is great";
??????????? XmlSerializer xmls = new XmlSerializer(typeof(MyObject));
??????????? StreamWriter sw = new StreamWriter("c:\\myobject.xml");
??????????? xmls.Serialize(sw,obj);
??????????? sw.Close();
??????? }
??????? public MyObject DSeriaByXml()
??????? {
??????????? XmlSerializer xmls = new XmlSerializer(typeof(MyObject));
??????????? FileStream fs = new FileStream("c:\\myobject.xml",FileMode.Open);
??????????? MyObject obj=(MyObject)xmls.Deserialize(fs);
??????????? fs.Close();
??????????? return obj;
??????? }
??? }
}
最后創建TEST 窗體事件
?
哈哈 ,ok 了 試試做一下吧。
?
轉載于:https://www.cnblogs.com/xiaogelove/archive/2010/04/21/1717451.html
總結
- 上一篇: 4年提升超200位!小米成《财富》世界5
- 下一篇: c#扩展方法奇思妙用高级篇四:对扩展进行