C# 序列化

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 序列化
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Person p = new Person();
            p.Name ="张三";
            p.Age =18;
            p.Gender = true;
            
            using (System.IO.FileStream file = new FileStream("person.dat", FileMode.Create, FileAccess.Write))
            {
                //System.Runtime.Serialization.Formatters.Binary;
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(file, p);  //序列化
            }
            MessageBox.Show("ok");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            using (System.IO.FileStream file = new FileStream("person.dat", FileMode.Open, FileAccess.Read))
            {
                BinaryFormatter b = new BinaryFormatter();
                Person p = (Person)b.Deserialize(file);  //反序列化

                MessageBox.Show(p.Name);
            }
        }
    }
    //程序集“序列化, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中的类型“序列化.Person”未标记为可序列化。
    [Serializable]
    public class Person
    {
        private string name;
        private int age;
        private bool gender;

        public bool Gender
        {
            get { return gender; }
            set { gender = value; }
        }

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

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

    }
}

 

C# 序列化

上一篇:SUM() 函数


下一篇:LVGL的使用:运行LVGL的PC模拟器例程