• 对象序列化和反序列化


    一、 二进制序列化:

          对象的序列化是将对象转换为二进制数据(字节流),反序列化是将二进制数据还原为对象。

          BinaryFormatter

        将对象序列化到stream: void Serialize( Stream,object pdj )

        将对象从stream 中反序列化,返回值为反序列化得到的对象:   object Deserialize(Stream stream )

      

        [Serializable]
        class Person
        {
            public int Age { get; set; }
            public  string Name { get; set; }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("请输入您的姓名:");
                string name= Console.ReadLine();
                Console.WriteLine("请输入您的年龄:");
                string age = Console.ReadLine();
    
                Person p = new Person();
                p.Name = name;
                p.Age =Convert.ToInt32(age);
    
                //序列化,写入流
                BinaryFormatter binFor = new BinaryFormatter();
                using (FileStream fs = File.OpenWrite("d:/temp/data.data"))
                {
                    binFor.Serialize(fs, p); //把p指向的对象序列化保存到fs流中
                }
                //反序列化,读入流
                BinaryFormatter binFor2 = new BinaryFormatter();
                using (FileStream fs = File.OpenRead("d:/temp/data.data"))
                {
                   Person p1=(Person)binFor2.Deserialize(fs); //把p指向的对象序列化保存到fs流中
                    Console.WriteLine(p1.Age + p1.Name);
                }
                Console.ReadKey();
    
            }
        }

     可序列化的类注意事项:

        要序列化的类型必须标记为:[Serializable]

             该类型的父类也必须标记为:[Serializable]

              该类型中的所有成员的类型也必须标记为:[Serializable]

    为什么要序列化:

               保持对象的持久化,将复杂的对象转换,方便我们的存储与信息交换

  • 相关阅读:
    MYSQL主从同步故障一例及解决过程
    mysql主从复制
    I want a mysqldump –ignore-database option
    MYSQL使用mysqldump导出某个表的部分数据
    Linux MySQL主从复制(Replication)配置
    mysql mysqldump只导出表结构或只导出数据的实现方法
    Mysql导出表结构及表数据 mysqldump用法
    MVC 数据验证
    JS中call、apply的用法说明
    js 与或运算符 || && 妙用
  • 原文地址:https://www.cnblogs.com/fuyouchen/p/9365814.html
Copyright © 2020-2023  润新知