序列化与反序列化的用法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> listPers = new List<Person>();
            Person per1 = new Person("张三", 18);
            Person per2 = new Person("李四", 20);
            listPers.Add(per1);
            listPers.Add(per2);
            SerializeMethod(per1 );
            ReserializeMethod();
            Console.ReadKey();
        }

        static void ReserializeMethod()
        {
            using (FileStream fs = new FileStream("1.bin", FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                Person list = bf.Deserialize(fs) as Person;
            }
        }

        static void SerializeMethod(Person  listpers)

        {
            using (FileStream fs = new FileStream("1.bin", FileMode.OpenOrCreate))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, listpers);
            }
        }
    }

    [Serializable]
    class Person
    {
        public Person() { }
        public Person(string name, int age)
        {
            this.Name = name; this.Age = age;
        }

        private string name;

        public string Name { get => name; set => name = value; }

        [NonSerialized]
        private int age;//不序列化该对象

        public int Age { get => age; set => age = value; }

        public void SayHi() { Console.WriteLine("大家好,我是{0},今年{1}岁", name, age); }

    }
}

posted @ 2022-08-23 19:03  冰糖小袁子  阅读(36)  评论(0)    收藏  举报