点滴积累【C#】---序列化和反序列化

2018-06-23 21:57:04来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

序列化和反序列化效果图:

序列化和反序列化代码:

需要添加两个命名空间:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

List<Game> allgame = new List<Game>();
        private void button1_Click(object sender, EventArgs e)
        {
            string name = textBox1.Text.Trim();
            string type = textBox2.Text.Trim();
            string time = textBox3.Text.Trim();
            Game gm = new Game(name, type, time);
            allgame.Add(gm);
            MessageBox.Show("添加成功");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream("game.bin", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, allgame);
            fs.Close();
            MessageBox.Show("序列化成功");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Form1 from = new Form1();
            from.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //反序列化
            FileStream fs = new FileStream("game.bin", FileMode.Open);
            BinaryFormatter bf = new BinaryFormatter();
            List<Game> gm = (List<Game>)bf.Deserialize(fs);
            fs.Close();

            foreach (Game game in gm)
            {
                textBox4.Text += game.Name + " " + game.Type + " " + game.Time;
            }
        }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:表达式树基础

下一篇:How can I use Server.MapPath() from global.asax?