• C# 之二进制序列化


    序列化:又称串行化,是.NET运行时环境用来支持用户定义类型的流化的机制。其目的是以某种存储形成使自定义对象持久化,或者将这种对象从一个地方传输到另一个地方。

    一般有三种方式:1、是使用BinaryFormatter进行串行化二进制序列化;2、使用XmlSerializer进行串行化的XML序列化;3、使用SOAP协议进行序列化。这里先总结二进制序列化。

    命名空间:

    System.Runtime.Serialization.Formatters.Binary;
    System.IO;

    1).先建一个可序列化的类

      [Serializable]     
       class Person
        {
    private string name; public string Name { get { return name; } set { name = value; } }
    [NonSerialized]
    //age这个字段不序列化 private int age; public int Age { get { return age; } set { age = value; } }
    public Person() { } public Person(string name ,int age)
      {
    this.name = name; this.age = age; } public void say()
      { Console.WriteLine(
    "hello,my name is{0} ,I am {1}years old.",name,age); }
    }

    Main函数里:

    static void Main(string[] args)
            {
                List<Person> persons = new List<Person>();
                Person p1 = new Person("chen", 24);
                Person p2 = new Person("li", 23);
                persons.Add(p1);
                persons.Add(p2);
    
                xuliehua(persons); //调用静态序列化方法
                fanxuliehua();       //调用静态反序列化方法
    
    
                Console.ReadKey();
            }
    
            public static void xuliehua(List<Person> persons)//序列化方法
            {
                FileStream fs = new FileStream("Person.bin", FileMode.Create);//创建一个文件流,对文件进行写入
                BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
                bf.Serialize(fs, persons); //序列化到硬盘
                fs.Close();//关闭文件流
            }
    
            public static void fanxuliehua()//反序列化方法
            {
    
                FileStream fs = new FileStream("Person.bin", FileMode.Open);//打开流文件
                BinaryFormatter bf = new BinaryFormatter();
                List<Person> persons = bf.Deserialize(fs) as List<Person>;//从硬盘反序列化  
    
                //或  Person p=(Person)bf.Deserialize(fs); 对应上面的或者
    
                fs.Close();//关闭文件流
                for (int i = 0; i < persons.Count; i++)
                {
                    persons[i].say();
                }
            }

    结果:

    name 序列化过,而 age没有序列化,所以为0。

  • 相关阅读:
    ios xib或storyBoard的那些小方法
    ios pod库更新到1.0或1.0.1之正确修改podfile文件
    ios UILabel在storyBoard或xib中如何在每行文字不显示完就换行
    ios NSThred多线程简单使用
    Xcode升级插件失效,与添加插件不小心点击Skip Bundle解决办法
    ios app打ipa包
    极光推送碰到的问题
    ios 更新约束
    ios 缺少合规证明
    Path Sum II
  • 原文地址:https://www.cnblogs.com/jiangshuai52511/p/7793505.html
Copyright © 2020-2023  润新知