在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文件反序列化为对象。
上一篇:数据库中set和select的区别是什么
下一篇:什么是Apache Pig
C









