zoukankan      html  css  js  c++  java
  • .net学习笔记--序列化与反序列化

    序列化其实就是将一个对象的所有相关的数据保存为一个二进制文件(注意:是一个对象)

    而且与这个对象相关的所有类型都必须是可序列化的所以要在相关类中加上 [Serializable]特性

    对象类型包括:对象本身包含的类型,父类

    拥有需要的对象之后:1.将对象转换为二进制数据 使用专门的对像进行转换 BinaryFormatter

                                         2.将二进制数据写入到文件 FileSteam

    反序列化则是把二进制文件转换为一个对象

    例子代码如下:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.IO;
     7 using System.Runtime.Serialization.Formatters.Binary;
     8 namespace ConsoleApplication1
     9 {
    10     class Program
    11     {
    12         static void Main(string[] args)
    13         {
    14             Person per;//将要被序列化的对象
    15             Console.WriteLine("------序列化与反序列化------");
    16             Console.WriteLine("是否读取已经序列化的对象per");
    17             string str = Console.ReadLine();
    18             if (str == "yes")
    19             {
    20                 if (!File.Exists("save.bin"))
    21                 {
    22                     Console.WriteLine("你还没有将per序列化");
    23                     return;
    24                 }
    25                 using (FileStream fs = new FileStream("save.bin", FileMode.Open))
    26                 {
    27                     BinaryFormatter bf = new BinaryFormatter();
    28                     per = bf.Deserialize(fs) as Person;//将二进制数据转换为per对象
    29                     per.SayHi();
    30                     Console.ReadLine();
    31                 }
    32             }
    33             else
    34             {
    35                 per = new Person();
    36                 per.Name = "小李";
    37                 using(FileStream fs=new FileStream("save.bin",FileMode.Create))
    38                 {
    39                     BinaryFormatter bf = new BinaryFormatter();
    40                     bf.Serialize(fs,per);//将per对象转换成二进制数据,并保存。
    41                     Console.WriteLine("序列化成功");
    42                     Console.ReadLine();
    43                 }
    44             }
    45                 
    49         }
    50     }
    51     [Serializable]
    52     class Person
    53     {
    54         public string Name;
    55         public void SayHi()
    56         {
    57             Console.WriteLine("hello {0}",Name);
    58         }
    59     }
    60 }
  • 相关阅读:
    树莓派3的无线设置
    Zabbix监控
    使用mutt+msmtp在Linux命令行界面下发邮件(续)
    K8S(16)集成实战-使用spinnaker进行自动化部署
    K8S(15)监控实战-ELK收集K8S内应用日志
    K8S(14)监控实战-grafana出图_alert告警
    K8S(13)监控实战-部署prometheus
    K8S(12)配置中心实战-多环境交付apollo三组件
    K8S(11)配置中心实战-单环境交付apollo三组件
    K8S(10)配置中心实战-configmap资源
  • 原文地址:https://www.cnblogs.com/CodeFaker/p/3900133.html
Copyright © 2011-2022 走看看