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 }
  • 相关阅读:
    牌库读取的修复
    法术迸发(Spellburst)
    传染孢子的探索
    降低电脑功耗——降低笔记本风扇噪音
    Playfield 类方法的注释
    大陆争霸( 最短路变形)
    POJ 2406 Power String
    括号匹配
    HDU 1003 最大子段和
    6.19noip模拟赛总结
  • 原文地址:https://www.cnblogs.com/hudean/p/11717086.html
Copyright © 2011-2022 走看看