如何用域名访问网站,昆明软件开发公司,微信小程序设计软件,数据分析师要学什么课程序列化#xff1a;是将对象的状态存储到特定存储介质的过程#xff0c;也可以说是将对象状态转换为可保持或传输的格式的过程。 上面的解释是官方定义#xff0c;大白话解释就是#xff0c;将对象以二进制的方式存储在文件中#xff0c;如果简简单单的将一些数据或者内容存…序列化是将对象的状态存储到特定存储介质的过程也可以说是将对象状态转换为可保持或传输的格式的过程。 上面的解释是官方定义大白话解释就是将对象以二进制的方式存储在文件中如果简简单单的将一些数据或者内容存储到文件中的话很好实现直接使用IO就可以但是对象可就不一样了我们可以通过序列化来实现下面就展示一个序列化的案例 首先新建一个Student类需要注意的是在类的上方要标识[Serializable],以表示该类可支持序列化操作。 [Serializable]public class Student{public int Id { get; set; }public string Name { get; set; }public string Sex { get; set; }public int Age { get; set; }public Student() { }public Student(string name,int age,string sex) {this.Name name;this.Age age;this.Sex sex;}public void Say() {Console.WriteLine(姓名是{0}年龄是{1}性别是{2},Name,Age,Sex);}}接下来写一个测试类实现一下序列化
static void TestXu() {ListStudent slist new ListStudent();Student stu1 new Student(刘世豪,12,男);Student stu2 new Student(李宏洋, 18, 男);Student stu3 new Student(钟立琦,19,男);slist.Add(stu1);slist.Add(stu2);slist.Add(stu3);//开始序列化using(FileStream fs new FileStream(d:/test/test.txt,FileMode.Create)){BinaryFormatter bf new BinaryFormatter();bf.Serialize(fs,slist);Console.WriteLine(序列化成功);}}执行一下运行结果不出意外的话是序列化成功但是提醒你不要去看生成的那个文件不信的话你就去看看。 反序列化顾名思义就是与序列化相反也就是从文件中将对象在还原回来。 下面是代码案例
static void FanXulie() { using(FileStream fs new FileStream(d:/test/test.txt,FileMode.Open)){BinaryFormatter bf new BinaryFormatter();ListStudent slist (ListStudent)bf.Deserialize(fs);foreach (Student stu in slist) {Console.WriteLine(stu.Name);}}}
输出的运行结果 刘世豪 李宏洋 钟立琦
这就是序列化和反序列化操作的案例。 **
欢迎关注微信公众号《雄雄的小课堂》呦。
**