zoukankan      html  css  js  c++  java
  • C#中的序列化和反序列化

    序列化:是将对象的状态存储到特定存储介质的过程,也可以说是将对象状态转换为可保持或传输的格式的过程。
    上面的解释是官方定义,大白话解释就是,将对象以二进制的方式存储在文件中,如果简简单单的将一些数据或者内容存储到文件中的话,很好实现,直接使用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() {
                List<Student> slist = new List<Student>();
                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();
                    List<Student> slist = (List<Student>)bf.Deserialize(fs);
                    foreach (Student stu in slist) {
                        Console.WriteLine(stu.Name);
                    }
                }
            }
       
    

    输出的运行结果:
    刘世豪
    李宏洋
    钟立琦

    这就是序列化和反序列化操作的案例。
    **

    欢迎关注微信公众号:《雄雄的小课堂》呦。

    **

  • 相关阅读:
    TCP通信 小例子
    Socket的简单使用
    Redis练习
    资料
    Redis封装帮助类
    使用Redis的基本操作
    Redis配置主从
    Redis基本设置
    clientHeight ,offsetHeight,style.height,scrollHeight的区别与联系
    服务器操作之如何绑定网站
  • 原文地址:https://www.cnblogs.com/a1111/p/12815851.html
Copyright © 2011-2022 走看看