zoukankan      html  css  js  c++  java
  • 序列化与反序列化

    所谓序列化就是把一个对象转换为二进制格式,反序列化相反,从一个二进制格式对象转换为自定义类型。

    序列化步骤:

    1.定义一个个类,用[Serializable]标注在类上面

    2.定义一个写文件流

    3.定义一个二进制转换对象BinaryFormatter

    4.序列化

    反序列化步骤:

    1.声明一个对象

    2.定义一个读文件流

    3.定义一个二进制转换对象BinaryFormatter

    4.反序列化

    5.存储到声明的对象中

     1 using System;
     2 using System.IO;
     3 using System.Runtime.Serialization.Formatters.Binary;
     4 
     5 namespace LearnSerializable
     6 {
     7     [Serializable]
     8     public class Person
     9     {
    10         public Person() { }
    11         public Person(string name, int age)
    12         {
    13             Name = name;
    14             Age = age;
    15         }
    16         public string Name { set; get; }
    17         public int Age { set; get; }
    18     }
    19     class Program
    20     {
    21         private string path = @"E:AdvanceCSharpProjectLearnCSharpTestSerializable.txt";
    22         private void TestSerializable()
    23         {
    24             //定义一个类对象
    25             Person dog = new Person("BlackTeeth", 2);
    26             //定义一个文件流
    27             using (FileStream fsw = new FileStream(path, FileMode.OpenOrCreate))
    28             {
    29                 //定义一个二进制格式化对象
    30                 BinaryFormatter bf = new BinaryFormatter();
    31                 //序列化
    32                 bf.Serialize(fsw, dog);
    33             }
    34 
    35 
    36         }
    37         private void TestDeserializable()
    38         {
    39             //声明一个类对象
    40             Person dog = null;
    41             //定义一个文件流
    42             using (FileStream fsr = new FileStream(path, FileMode.Open))
    43             {
    44                 //定义一个二进制格式化对象
    45                 BinaryFormatter bf = new BinaryFormatter();
    46                 //反序列化赋值给声明的对象
    47                 dog = bf.Deserialize(fsr) as Person;
    48            
    49             }
    50             Console.WriteLine(dog.Name + "," + dog.Age);
    51 
    52         }
    53         static void Main(string[] args)
    54         {
    55             new Program().TestSerializable();
    56             new Program().TestDeserializable();
    57         }
    58     }
    59 }
  • 相关阅读:
    倒排索引压缩
    记一次java内存溢出的解决过程
    [译]ES读写文档时shard-replication模型
    [转载]抓包工具Charles乱码解决办法
    Mac 快捷键整理(不定期更新)
    高效能人士执行的四原则(2017-12-15)
    scala sbt 添加国内镜像
    maven工程小红叉处理方法
    系统管理中 bash shell 脚本常用方法总结
    scala 2.11报错error: not found: type Application
  • 原文地址:https://www.cnblogs.com/blackteeth/p/10205242.html
Copyright © 2011-2022 走看看