C#:淺談使用XML實現序列化
阿新 • • 發佈:2018-06-23
反序 student stat 類型 接口 ML tst In ise 序列化是將一個對象轉換成字節流以達到將其長期保存在內存、數據庫或文件中的處理過程。它的主要目的是保存對象的狀態以便以後需要的時候使用。與其相反的過程叫做反序列化。
序列化一個對象
為了序列化一個對象,我們需要一個被序列化的對象,一個容納被序列化了的對象的(字節)流和一個格式化器。進行序列化之前我們先看看System.Runtime.Serialization名字空間。ISerializable接口允許我們使任何類成為可序列化的類。
如果我們給自己寫的類標識[Serializable]特性,我們就能將這些類序列化。除非類的成員標記了[NonSerializable],序列化會將類中的所有成員都序列化。
序列化的類型
二進制(流)序列化
SOAP序列化(使用IXmlSerializable)
XML序列化
通常大部分都是使用的XML序列化,所以介紹一下使用XML序列化.
Student類
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace XmlSerializers
{
[Serializable]
public class Student
{
private string name;
public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } private string hoddy; public string Hoddy { get { return hoddy; } set { hoddy = value; } } public Student() { } public Student(string name,int age,string hoddy) { this.Name = name; this.Age = age; this.Hoddy = hoddy; } public void SayHi() { string mess = string.Format("我是{0},年齡有{1},愛好是{2}", Name, Age, Hoddy); Console.WriteLine(mess); } }
}
Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
namespace XmlSerializers
{
[Serializable]
class Program
{
static List<Student> students = new List<Student>(); static void Main(string[] args) { //添加學生 InitStudent(); //序列化 Serialize(); //反序列化 Deserialize(); Console.ReadLine(); } public static void InitStudent() { Student scoficedld = new Student("scofield", 28, "哈哈"); Student su = new Student("程沐喆", 34, "寫博客"); Student zhang = new Student("張婧", 21, "唱歌"); Student huang = new Student("黃飛鴻", 25, "打架"); Student ding = new Student("丁俊暉", 30, "打斯諾克"); Student sullivan = new Student("OSullivan", 33, "打147"); Student Jay = new Student("周傑", 21, "耍雙節棍"); students.Add(scoficedld); students.Add(su); students.Add(zhang); students.Add(huang); students.Add(ding); students.Add(sullivan); students.Add(Jay); } public static void Serialize() { FileStream fs = new FileStream("Serialize.xml", FileMode.Create); XmlSerializer xs = new XmlSerializer(typeof(List<Student>)); xs.Serialize(fs, students); fs.Close(); } public static void Deserialize() { FileStream fs = new FileStream("Serialize.xml", FileMode.Open); XmlSerializer xs = new XmlSerializer(typeof(List<Student>)); List<Student> lists = xs.Deserialize(fs) as List<Student>; if (lists != null) { for (int i = 0; i < lists.Count; i++) { lists[i].SayHi(); } } fs.Close(); } }
}
C#:淺談使用XML實現序列化