C# 序列化 与 反序列化

在C#中 MF 为我们提供了XmlSerializer这个类 ,来方便我们实现序列化和反序列化的操作。那什么是序列化和反序列化呢? 序列化简单来说就是将程序中的对象实例转化为流存储(.xml文件),那么反序列化固然就是将 xml文件转化为对象的实例。

下面请看代码:

        private void XmlSerializerMethod()
        {
            XmlSerializer xs = new XmlSerializer(typeof(ListClass));

            Stream stream = new FileStream("TestXml.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

            ListClass listClass = new ListClass();
            listClass.listClassSerialize.Add(new ClassSerialization(){Name="Hi",Year=23,Sex="男"});
            listClass.listClassSerialize.Add(new ClassSerialization(){Name="Hi2",Year=21,Sex="男"});
            listClass.listClassSerialize.Add(new ClassSerialization(){Name="Hi23",Year=24,Sex="男"});
            listClass.listClassSerialize.Add(new ClassSerialization(){Name="Hi3",Year=22,Sex="男"});
            listClass.listClassSerialize.Add(new ClassSerialization(){Name="Hi1",Year=25,Sex="女"});
            listClass.listClassSerialize.Add(new ClassSerialization(){Name="Hi5",Year=17,Sex="女"});
            

            if(stream != null)
            {
                xs.Serialize(stream, listClass);
                stream.Close();
                MessageBox.Show("Serialize success!");
            }
        }


 

   public class ClassSerialization
    {
        public string Name;
        public int Year;
        public string Sex;
        
    }


 

    public class ListClass
    {
        public List<ClassSerialization> listClassSerialize;

        public ListClass()
        {
            listClassSerialize = new List<ClassSerialization>();
        }
    }


序列化成功之后

反序列化:

        private void DeserializeXml()
        {
            XmlSerializer xs = new XmlSerializer(typeof(ListClass));
            Stream stream = new FileStream("TestXml.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

            if (stream != null)
            {
                ListClass ls = (ListClass)xs.Deserialize(stream);

            }


        }


 

 

展开阅读全文

没有更多推荐了,返回首页