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

c#的序列化与反序列化

时间:2015-05-26 21:29:29      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:c#   序列化   反序列化   serializab   binaryform   

序列化与反序列化

这个可以直接把对象转化为二进制进行存储与通信;
在需要序列化的类前加[Serializable],使用BinaryFormatter类来进行操作;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace 序列化与反序列化
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student("刘备",28,‘男‘);
            Student stu2;
            string file = @"E:\code\test\test1.txt";
            using (FileStream fsWriter=new FileStream(file,FileMode.OpenOrCreate,FileAccess.Write))
            {
                //下面对stu进行序列化;
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fsWriter, stu);
            }
            using (FileStream fsReader=new FileStream(file,FileMode.Open,FileAccess.Read))
            {
                //下面进行反序列话;
                BinaryFormatter bf = new BinaryFormatter();
                stu2 = (Student)bf.Deserialize(fsReader);
            }
            Console.WriteLine("{0}今年{1}岁,是个{2}生",stu2.Name,stu2.Age,stu2.Gender);
            Console.ReadKey();


        }
    }
    [Serializable]
    public class Student
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
        private char _gender;

        public char Gender
        {
            get { return _gender; }
            set { _gender = value; }
        }
        public Student(string name,int age,char gender)
        {
            Name = name;
            Age = age;
            Gender = gender;
        }
    }
}

c#的序列化与反序列化

标签:c#   序列化   反序列化   serializab   binaryform   

原文地址:http://blog.csdn.net/zhzz2012/article/details/46011957

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