温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#序列化

发布时间:2020-04-13 21:29:12 来源:网络 阅读:421 作者:全智贤 栏目:编程语言

//实体类

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestOne
{
    [Serializable]//表示本类可序列化
   public class student
    {
        public string Name { get; set; }
        public string Sex { get; set; }
        public string Hobby { get; set; }
        //有参构造
        public student(string name, string sex, string hobby)
        {
            this.Name = name;
            this.Sex = sex;
            this.Hobby = hobby;
        }
       //无参构造
        public student() { }
    }
}
 
//窗体类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
//引入binaryformater类的命名空间
using System.Runtime.Serialization.Formatters.Binary;
 
namespace TestOne
{
    public partial class Form1 : Form
    {
        private List<student> stus = new List<student>();
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            stus.Add(new student("小张","男","打酱油"));
            stus.Add(new student("小明", "女", "玩游戏"));
            stus.Add(new student("小王", "男", "打酱油"));
            //将list集合序列化
            Save();
            //清除list集合中所有元素
            stus.Clear();
            //反序列话
            load();
            //绑定数据源
            dataGridView1.DataSource = new BindingList<student>(stus); 
        }
        //序列号方法
        public void Save()
        {
            //AppDomain.CurrentDomain.BaseDirectory返回一个字符串,为程序的运行时目录
            FileStream stream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "one.xml", FileMode.Create);
            //创建序列号对象
            BinaryFormatter binary = new BinaryFormatter();
            //将对象序列化到指定的文件中
            binary.Serialize(stream, this.stus);
            //关闭文件流
            stream.Close();
        }
        //反序列话
        public void load()
        { 
            //创建文件流对象
            FileStream stream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "one.xml", FileMode.Open);
            //创建序列号对象
            BinaryFormatter binary = new BinaryFormatter();
            //因为Deserialize()方法,返回的是一个object对象,所以要转型
            this.stus = (List<student>)binary.Deserialize(stream) ;
            //关闭文件流
            stream.Close();
        }
    }
}
 
附件:http://down.51cto.com/data/2359833
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI