首頁  >  文章  >  Java  >  c#的序列化與反序列化

c#的序列化與反序列化

黄舟
黄舟原創
2016-12-27 13:56:481146瀏覽

序列化與反序列化

這個可以直接把物件轉換成二元來儲存與通訊;
在需要序列化的類別前加上[Serializable],使用BinaryFormatter類別來進行操作;

<code class="language-c# hljs cs">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,&#39;男&#39;);
            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;
        }
    }
}
</code>
 以上就是c#的序列化與反序列化的內容,更多相關內容請關注PHP中文網(www.php.cn)!



陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn