在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文件反序列化為對象。