资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

C#序列化

//实体类

成都创新互联是一家专业提供滨海新区企业网站建设,专注与成都网站设计、网站建设、外贸网站建设H5开发、小程序制作等业务。10年已为滨海新区众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。

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 stus = new List();
        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(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)binary.Deserialize(stream) ;
            //关闭文件流
            stream.Close();
        }
    }
}
 
附件:http://down.51cto.com/data/2359833

新闻标题:C#序列化
文章URL:http://cdkjz.cn/article/jdipch.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220