在C#中,可以使用[System.Serializable]或者使用DataContract和DataMember属性来序列化实体类。
使用[System.Serializable]属性:
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
使用DataContract和DataMember属性:
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
在序列化时,可以使用XmlSerializer或者DataContractSerializer类来序列化实体类对象:
Person person = new Person { Name = "Alice", Age = 30 };
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (TextWriter writer = new StreamWriter("person.xml"))
{
serializer.Serialize(writer, person);
}
// 或者使用DataContractSerializer
DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(Person));
using (FileStream fileStream = new FileStream("person.xml", FileMode.Create))
{
dataContractSerializer.WriteObject(fileStream, person);
}
需要注意的是,若要序列化的类中包含其他类的实例,这些类也需要进行序列化的设置。