码迷,mamicode.com
首页 > Windows程序 > 详细

C# 序列化

时间:2014-11-03 06:40:21      阅读:355      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   for   sp   div   

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# 序列化

标签:des   style   blog   io   color   ar   for   sp   div   

原文地址:http://www.cnblogs.com/han1982/p/4070364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!