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

本文介绍了一个使用C#实现序列化和反序列化的简单实例。通过该实例,用户可以添加游戏信息到列表中,并将这些信息保存到二进制文件中。此外,还展示了如何从文件中读取并反序列化这些游戏信息。

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

序列化和反序列化代码:

需要添加两个命名空间:
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;
            }
        }

 

转载于:https://www.cnblogs.com/xinchun/p/3438364.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值