zoukankan      html  css  js  c++  java
  • 自定义类序列化与反序列化二进制

     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 test
     9 {
    10     class Program
    11     {
    12         static void Main(string[] args)
    13         {
    14             //要将p这个对象 传输给对方电脑
    15             //Person p = new Person();
    16             //p.Name = "张三";
    17             //p.Age = 19;
    18             //p.Gender = '男';
    19             //using (FileStream fsWrite = new FileStream(@"C:UsersSpringRainDesktop111.txt", FileMode.OpenOrCreate, FileAccess.Write))
    20             //{ 
    21             //    //开始序列化对象
    22             //    BinaryFormatter bf = new BinaryFormatter();
    23             //    bf.Serialize(fsWrite, p);
    24             //}
    25             //Console.WriteLine("序列化成功");
    26             //Console.ReadKey();
    27 
    28             //接收对方发送过来的二进制 反序列化成对象
    29             Person p;
    30             using (FileStream fsRead = new FileStream(@"C:UsersSpringRainDesktop111.txt", FileMode.OpenOrCreate, FileAccess.Read))
    31             {
    32                 BinaryFormatter bf = new BinaryFormatter();
    33                 p = (Person)bf.Deserialize(fsRead);
    34             }
    35             Console.WriteLine(p.Name);
    36             Console.WriteLine(p.Age);
    37             Console.WriteLine(p.Gender);
    38             Console.ReadKey();
    39         }
    40     }
    41 
    42 
    43     [Serializable]
    44     public class Person
    45     {
    46         private string _name;
    47 
    48         public string Name
    49         {
    50             get { return _name; }
    51             set { _name = value; }
    52         }
    53 
    54 
    55         private char _gender;
    56 
    57         public char Gender
    58         {
    59             get { return _gender; }
    60             set { _gender = value; }
    61         }
    62 
    63         private int _age;
    64 
    65         public int Age
    66         {
    67             get { return _age; }
    68             set { _age = value; }
    69         }
    70     }
    71 }
  • 相关阅读:
    BZOJ 2588
    BZOJ 3524
    BZOJ 3932
    Bzoj1013--Jsoi2008球形空间产生器
    Codevs1743--反转卡片
    Bzoj1208--Hnoi2004宠物收养所
    Bzoj1112--Poi2008砖块Klo
    后缀自动机学习笔记
    Bzoj1588--Hnoi2002营业额统计
    Bzoj1056--Haoi2008排名系统
  • 原文地址:https://www.cnblogs.com/hudean/p/11717086.html
Copyright © 2011-2022 走看看