using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml.Serialization; namespace Serialize { class Program { static void Main(string[] args) { var key = Console.ReadLine(); switch (key) { case "1": Serialize(); break; case "2": DeSerialize(); break; case "3": DeSerializeList(); break; case "4": DeSerializeList(); break; } } /// <summary> /// 序列化一个对象 /// </summary> static void Serialize() { Users users = new Users(); users.Name = "Furysi"; users.Age = 25; users.Address = "ShangHai"; XmlSerializer xmlSerialize = new XmlSerializer(typeof(Users)); using (Stream stream = new FileStream("test.xml", FileMode.Create, FileAccess.Write)) { xmlSerialize.Serialize(stream, users); } Console.WriteLine("OK"); Console.ReadLine();//加这行是为了方便查看结果 } /// <summary> /// 反序列化一个对象 /// </summary> static void DeSerialize() { Users users = new Users(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(Users)); using (Stream stream = new FileStream("test.xml", FileMode.Open, FileAccess.Read)) { users = (Users)xmlSerializer.Deserialize(stream); } Console.WriteLine("Name:" + users.Name); Console.WriteLine("Age:" + users.Age); Console.WriteLine("Address:" + users.Address); Console.ReadLine();//加这行是为了方便查看结果 } /// <summary> /// 序列化一个集合 /// </summary> static void SerializeList() { List<Users> list = new List<Users>() { new Users(){ Name="AAA",Age=25,Address="ShangHai"}, new Users(){ Name="BBB",Age=26,Address="BeiJing"}, new Users(){ Name="CCC",Age=27,Address="ShenZhen"} }; XmlSerializer xmlSerialize = new XmlSerializer(typeof(List<Users>)); using (Stream stream = new FileStream("test.xml", FileMode.Create, FileAccess.Write)) { xmlSerialize.Serialize(stream, list); } Console.WriteLine("OK"); Console.ReadLine();//加这行是为了方便查看结果 } /// <summary> /// 反序列化一个集合 /// </summary> static void DeSerializeList() { List<Users> list = new List<Users>(); Users users = new Users(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Users>)); using (Stream stream = new FileStream("test.xml", FileMode.Open, FileAccess.Read)) { list = (List<Users>)xmlSerializer.Deserialize(stream); } foreach (var item in list) { Console.WriteLine("Name:" + item.Name); Console.WriteLine("Age:" + item.Age); Console.WriteLine("Address:" + item.Address); } Console.ReadLine();//加这行是为了方便查看结果 } } public class Users { public string Name { get; set; } public int Age { get; set; } public string Address { get; set; } } }
序列化是将对象转换为字节流以将其保存在内存、数据库或文件中的过程。其主要目的是保存对象的状态,以便可以在需要时重新创建对象。相反的过程称为反序列化。
对象被序列化为流。流传递的不仅是数据,还包括有关对象类型的信息,如对象的版本、区域性和程序集名称。通过该流,可以将对象存储在数据库、文件或内存中。
通过序列化,开发人员还可以执行类似如下的操作:通过 Web 服务将对象发送到远程应用程序、将对象从一个域传递到另一个域、以 XML 字符串的形式跨防火墙传递对象,或者跨应用程序维护安全信息或用户特定信息。