2015年11月27日 星期五

C16_4 自行訂議序列化類別

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;
namespace C16_4
{
    ///
    ///自行訂議序列化類別
    ///
    [Serializable]
    public class Employee : ISerializable
    {
        public int EmpId = 100;
        public string EmpName = "老王";
        public Employee()
        { }
        private Employee(SerializationInfo info, StreamingContext ctxt)
        {
            EmpId = (int)info.GetValue("EmployeeId",typeof(int));
            EmpName = (String)info.GetValue("EmployeeName",typeof(string));
        }
        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
        {
            info.AddValue("EmployeeId",EmpId);
            info.AddValue("EmployeeName",EmpName);
        }
    }
    public class Test
    {
        ///
        ///BinaryFormatter 進行序列化
        ///
        public void DoSerialize()
        {
            Employee mp = new Employee();
            mp.EmpId = 10;
            mp.EmpName = "老張";
            Stream steam = File.Open("c:\\Employee.dat",FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(steam,mp);
            steam.Close();
        }
        ///
        ///BinaryFormatter進行反序列化
        ///
        public void DoDeserialize()
        {
            Stream steam = File.Open("c:\\Employee.dat",FileMode.Open);
            BinaryFormatter bf = new BinaryFormatter();
            Employee mp = (Employee)bf.Deserialize(steam);
            steam.Close();
            Console.WriteLine(mp.EmpId);
            Console.WriteLine(mp.EmpName);
        }
        public static void Main()
        {
            Test test = new Test();
            test.DoSerialize();
            test.DoDeserialize();
        }
    }
}

沒有留言: