序例化和反序列化ArrayList(ArrayList里存放自定义类型)

来源:互联网 发布:媒体数据库 编辑:程序博客网 时间:2024/06/18 09:05

       //序例化

        private void button4_Click(object sender, EventArgs e)
        {
            string[] str = new string[3];                   //自定义类型
            str[0] = "LR5001";
            str[1] = "LR5002";
            str[2] = "LR5003";

            int[] intarr = new int[3];                        //自定义类型
            intarr[0] = 0;
            intarr[1] = 1;
            intarr[2] = 2;


            ArrayList arraylist = new ArrayList();
            arraylist.Add(1);
            arraylist.Add("MyName");
            arraylist.Add(str);
            arraylist.Add(intarr);
            try
            {
                Type[] type=new Type[2];
                type[0] = str.GetType();
                type[1] = intarr.GetType();
                XmlSerializer xmlserializer = new XmlSerializer(typeof(ArrayList),type);
                FileStream fs = new FileStream("D://xml.xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                xmlserializer.Serialize(fs, arraylist);
                fs.Close();
                MessageBox.Show("序例化成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

       //反序例化

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                Type[] type = new Type[2];
                type[0] = Type.GetType("System.String[]");
                type[1] = Type.GetType("System.Int32[]");
                XmlSerializer xmlserializer = new XmlSerializer(typeof(ArrayList), type);
                FileStream fs = new FileStream("D://xml.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                ArrayList arraylist = (ArrayList)xmlserializer.Deserialize(fs);
                fs.Close();
                MessageBox.Show("反序例化成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

原创粉丝点击