C#中怎么实现对象的序列化和反序列化

avatar
作者
筋斗云
阅读量:0

在C#中,可以通过使用System.Runtime.Serialization命名空间中的DataContractSerializer类来实现对象的序列化和反序列化。

序列化对象示例代码:

using System; using System.IO; using System.Runtime.Serialization;  [DataContract] public class Person {     [DataMember]     public string Name { get; set; }          [DataMember]     public int Age { get; set; } }  class Program {     static void Main()     {         Person person = new Person { Name = "Alice", Age = 30 };          DataContractSerializer serializer = new DataContractSerializer(typeof(Person));         using (FileStream stream = new FileStream("person.xml", FileMode.Create))         {             serializer.WriteObject(stream, person);         }     } } 

反序列化对象示例代码:

using System; using System.IO; using System.Runtime.Serialization;  class Program {     static void Main()     {         DataContractSerializer serializer = new DataContractSerializer(typeof(Person));         using (FileStream stream = new FileStream("person.xml", FileMode.Open))         {             Person person = (Person)serializer.ReadObject(stream);             Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");         }     } } 

以上代码中,Person类使用DataContractDataMember属性来标记需要序列化的属性,然后通过DataContractSerializer类将对象序列化为XML文件或从XML文件反序列化为对象。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!