阅读量: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
类使用DataContract
和DataMember
属性来标记需要序列化的属性,然后通过DataContractSerializer
类将对象序列化为XML文件或从XML文件反序列化为对象。