C#序列化
//实体类
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
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。