c#的序列化與還原序列化,

來源:互聯網
上載者:User

c#的序列化與還原序列化,
序列化與還原序列化

這個可以直接把對象轉化為二進位進行儲存與通訊;
在需要序列化的類前加[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;        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.