- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Lesson2
- {
- [Serializable]
- public class Person
- {
- // 让用户输入姓名 年龄 性别 住址 邮箱 血型 职业 毕业学校
- private string _name;
- public string Name
- {
- get { return _name; }
- set { _name = value; }
- }
- private string _gender;
- public string Gender
- {
- get { return _gender; }
- set { _gender = value; }
- }
- private int _age;
- public int Age
- {
- get { return _age; }
- set { _age = value; }
- }
- private string _adress;
- public string Adress
- {
- get { return _adress; }
- set { _adress = value; }
- }
- private string _email;
- public string Email
- {
- get { return _email; }
- set { _email = value; }
- }
- private string _typeofblood;
- public string Typeofblood
- {
- get { return _typeofblood; }
- set { _typeofblood = value; }
- }
- private string _job;
- public string Job
- {
- get { return _job; }
- set { _job = value; }
- }
- private string _graduateSchool;
- public string GraduateSchool
- {
- get { return _graduateSchool; }
- set { _graduateSchool = value; }
- }
- }
- }
- 以上为Person类
- string path = @"D:\DiduTimes\CsharpSelfDoc\20121006\456.txt";//读取别人序列化后的记事本文档
- //比如456记事本中存的是" >Lesson2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Lesson2.Person _name_gender_age_adress_email_typeofblood_job_graduateSchool 绐﹀Ξ濠? 濂? 鍖椾含 douniwan@itcast.cn o 瀛︾敓 鍖楀ぇ";可以将引号里的内容粘贴到记事本文档中并命名为456.txt
- using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))//可读
- {
- BinaryFormatter bf = new BinaryFormatter();
- p = (Person)bf.Deserialize(fs);//反序列化,用里氏转换为Person类
- }
- Console.WriteLine(p.Name);
- Console.WriteLine(p.Age);
- Console.WriteLine(p.Gender);
- Console.WriteLine(p.Typeofblood);
- Console.WriteLine(p.Adress);
- Console.WriteLine(p.Email);
- Console.WriteLine(p.Job);
- Console.WriteLine(p.GraduateSchool);//输出实例化对象的信息
- Console.ReadKey();
- 序列化时,可写状态,bf.Serialize(fs, p);序列化时,参数除了要实例化后的文件流,还要输入实例化的对象名
- 反序列化时,可读状态,p = (Person)bf.Deserialize(fs);反序列化,只需要实例化后的文件流,但是需要里氏转换类型,然后用实例化的对象名来接收,通过对象.属性输出显示所存储的值.
复制代码 |