zoukankan      html  css  js  c++  java
  • 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函数里:

      List<Person> persons = new List<Person>();//或者 Person p=new Person("chen",24);
                Person p1 = new Person("chen",24);
                Person p2 = new Person("li", 23);
                persons.Add(p1);
                persons.Add(p2);

                xuliehua(persons); //调用静态序列化方法
                fanxuliehua();       //调用静态反序列化方法

         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();
                }
            }

    结果:hello,my name is chen ,I am 0years old.

            hello,my name is li ,I am 0years old.//name 序列化过,而 age没有序列化,所以为0.

    注意:继承时,父类与子类都需要序列化。

  • 相关阅读:
    New version of VS2005 extensions for SharePoint 3.0
    QuickPart : 用户控件包装器 for SharePoint Server 2007
    随想
    发布 SharePoint Server 2007 Starter Page
    如何在SharePoint Server中整合其他应用系统?
    Office SharePoint Server 2007 中文180天评估版到货!
    RMS 1.0 SP2
    SharePoint Server 2007 Web内容管理中的几个关键概念
    如何为已存在的SharePoint站点启用SSL
    Some update information about Office 2007
  • 原文地址:https://www.cnblogs.com/anyihen/p/5506988.html
Copyright © 2011-2022 走看看