直接上码:
首先创建class1类
public class Class1 { public string name { get; set; } public int age { get; set; } public bool sex { get; set; } }
实例化class1对象并进行序列化和反序列化
static void Main(string[] args) { //实例化class1类 Class1 c1 = new Class1() { name = "jia", age = 18, sex = true }; //序列化(class1为反序列化已知对象) XmlSerializer ser = new XmlSerializer(typeof(Class1)); // MemoryStream类是创建缓存以byte的形式临时存储数据 MemoryStream ms = new MemoryStream(); //将序列化对象c1序列化后缓存到ms对象中 ser.Serialize(ms, c1); //将缓存数据以utf8编码的形式读取并存入string对象(要保存的对象) string xmlString = Encoding.UTF8.GetString(ms.ToArray()); //释放缓存 ms.Dispose(); //反序列化(class1为反序列化已知对象) XmlSerializer dser = new XmlSerializer(typeof(Class1)); //读取到的以byte的形式存储的数据并以utf8编码的形式读取并存入string对象 Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)); //进行反序列化并转换为类对象 Class1 c2 = dser.Deserialize(xmlStream) as Class1; Console.Read(); }