zoukankan      html  css  js  c++  java
  • C# 序列化 Serialize 的应用

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.IO;
     6 using System.Runtime.Serialization.Formatters.Binary;
     7 
     8 namespace SerializeTest
     9 {
    10     class Program
    11     {
    12         static void Main(string[] args) {
    13             // Create a Person 
    14             Person ztc = new Person("ZhouTianChi", 32);
    15 
    16             // Serialize 将这个 Person 类的实例,写入到硬盘中保存
    17             using (FileStream fs = File.Create(@"D:person.txt")) {
    18                 // 使用的是 BinaryFormatter 类
    19                 BinaryFormatter bf = new BinaryFormatter();
    20                 // 的Serialize 方法
    21                 bf.Serialize(fs, ztc);
    22             }
    23 
    24             // 声音一个空的 Person 类,用来装载我们反Serialize后得到的对象 
    25             Person DeSerializeZTC;
    26             // DeSerialize
    27             using (FileStream fs = File.Open(@"D:person.txt",FileMode.Open)) {
    28                 // 使用 BinaryFormatter 类
    29                 BinaryFormatter bf = new BinaryFormatter();
    30                 // 的 Deserialize 方法
    31                 DeSerializeZTC = (Person)bf.Deserialize(fs);
    32 
    33                 DeSerializeZTC.SayHello();
    34             }
    35         }
    36     }
    37 
    38     // 这里我们定义一个 类, (可序列化的类,就是把类中的数据弄成流的形式)
    39     [Serializable]
    40     class Person {
    41         // NonSerialized 就是不将这个字段序列化.
    42         [NonSerialized]
    43         public string test = "asldkgjweg";
    44 
    45         public int Age { get; set; }
    46         public string Name { get; set; }
    47         public Person(string name, int age) {
    48             this.Age = age;
    49             this.Name = name;
    50         }
    51         public void SayHello() {
    52             Console.WriteLine("I am " + Name + ". And " + Age + " years old.");
    53         }
    54     }
    55 }


    Serialized 序列化 , 就是把类中的数据转化成流的形式. 这样, 可以存在硬盘中, 也可以在网络间传送.

  • 相关阅读:
    20135203齐岳 信息安全系统设计基础第二周学习总结
    信息安全系统设计基础第一周学习总结
    实验五 cmp传输与加解密
    实验三 敏捷开发与XP实践(改)
    Anaconda添加镜像和删除镜像
    srvany.exe和instsrv.exe打包exe为windows服务趟的坑
    python笔记
    haproxy实现socket5代理
    nginx实现的一些实用性配置,持续更新中
    利用Func封装“方法重试”功能
  • 原文地址:https://www.cnblogs.com/easyfrog/p/3151309.html
Copyright © 2011-2022 走看看