C#序列化
发表于:2024-11-26 作者:热门IT资讯网编辑
编辑最后更新 2024年11月26日,//实体类using System;using System.Collections.Generic; using System.Linq; using System.Text; namespace
//实体类
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