首頁 > 軟體

C#序列化與反序列化集合物件並進行版本控制

2022-09-12 18:00:51

當涉及到跨程序甚至是跨域傳輸資料的時候,我們需要把物件序列化和反序列化。

首先可以使用Serializable特性。

    [Serializable]
    public class Person
    {
        public string _firstName;
        public string _secondName;
        //序列化
        [OnSerializing]
        internal void OnSerializing(StreamingContext context)
        {
            _firstName = _firstName.ToUpper();
            _secondName = _secondName.ToUpper();
        }
        //反序列化
        [OnDeserialized]
        internal void OnDeserialized(StreamingContext context)
        {
            _firstName = _firstName.ToLower();
            _secondName = _secondName.ToLower();
        }
    }

當然,也可以實現ISerializable介面。在介面方法GetObjectData完成序列化,把資訊儲存到SerializationInfo中,在建構函式中反序列化,把資訊從SerializationInfo中讀取出來。

   [Serializable]
    public class Person : ISerializable
    {
        public string _firstName;
        public string _secondName;
        public Person()
        {
            
        }
        //反序列化
        public Person(SerializationInfo si, StreamingContext context)
        {
            _firstName = si.GetString("first").ToLower();
            _secondName = si.GetString("second").ToLower();
        }
        //序列化
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("first", _firstName.ToUpper());
            info.AddValue("second",_secondName.ToUpper());
        }
    }

對序列化和反序列化物件進行版本控制

下面的類,描述了物件的第一個版本。

[Serializable]
public class SomeClass : ISerializable
{
    private int a;
    public SomeClass(){}
    public SomeClass(SerializationInfo info, StreamingContext context)
    {
        a = info.GetInt32("myval");
    }
    public void GetObjectData(SerializationInfo, StreamingContext context)
    {
        info.AddValue("VERSION",1);
         info.AddValue("myval", a);
    }
}

現在SomeClass要增加一個私有欄位,成為版本二。

[Serializable]
public class SomeClass : ISerializable
{
    private int a;
    private string b;
    public SomeClass(){}
    public SomeClass(SerializationInfo info, StreamingContext context)
    {
        int VERSION = info.GetInt32("VERSION");
        a = info.GetInt32("a");
        if(VERSION > 1)
        {
            b = info.GetString("another");
        }
        else
        {
            b = "預設值";
        }
    }
    public void GetObjectData(SerializationInfo, StreamingContext context)
    {
        info.AddValue("VERSION",2);
         info.AddValue("myval", a);
         info.AddValue("another", b);
    }
}

把集合物件序列化到檔案並反序列化讀出

如果一個集合物件需要實現序列化和反序列化,那麼集合元素物件必須可以被序列化和反序列化,並且集合元素物件中的物件屬性也必須可以被序列化和反序列化,依此類推。

    [Serializable]
    public class Car : ISerializable
    {
        private string _model;
        private int _year;
        private Owner _owner;
        public Car()
        {
            
        }
        public Car(SerializationInfo info, StreamingContext context)
        {
            this._model = (string) info.GetValue("Model", typeof (string));
            this._year = (int) info.GetValue("Year", typeof (int));
            this._owner = (Owner) info.GetValue("Owner", typeof (Owner));
        }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Model",this._model);
            info.AddValue("Year", this._year);
            info.AddValue("Owner", this._owner);
        }
    }
    [Serializable]
    public class Owner : ISerializable
    {
        private string _name;
        public Owner()
        {
            
        }
        public Owner(SerializationInfo info, StreamingContext context)
        {
            this._name = (string) info.GetValue("Name", typeof (string));
        }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Name", this._name);
        }
    }

以上,我們想序列化Car的集合到檔案中,再反序列化Cars的集合讀取出來。那麼,我們必須讓Car可以被序列化和反序列化,Car的屬性物件Owner也必須可以被序列化和反序列化。

接著,用來封裝Car集合的一個類。

    [Serializable]
    public class CarsList : ISerializable
    {
        private List<Car> _cars;
        public List<Car> Cars
        {
            get { return this._cars; }
            set { this._cars = value; }
        }
        public CarsList()
        {
            
        }
        public CarsList(SerializationInfo info, StreamingContext context)
        {
            this._cars = (List<Car>) info.GetValue("Cars", typeof (List<Car>));
        }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Cars", this._cars);
        }
    }

針對CarsList寫一個序列化和反序列化的幫助類。

    public class SerializerHelper
    {
        public SerializerHelper()
        {
            
        }
        //序列化
        public void SerializeObject(string fileName, CarsList carsList)
        {
            //根據檔名開啟流
            Stream stream = File.Open(fileName, FileMode.Create);
            BinaryFormatter bFormatter = new BinaryFormatter();
            //把物件序列化到流中
            bFormatter.Serialize(stream,carsList);
            stream.Close();
        }
        //反序列化
        public CarsList DeserializeObject(string fileName)
        {
            CarsList carsList;
            //根據檔名開啟流
            Stream stream = File.Open(fileName, FileMode.Open);
            BinaryFormatter bfFormatter = new BinaryFormatter();
            carsList = (CarsList)bfFormatter.Deserialize(stream);
            stream.Close();
            return carsList;
        }
    }

在使用者端按如下呼叫:

        static void Main(string[] args)
        {
            List<Car> cars = new List<Car>();
            CarsList carsList = new CarsList();
            carsList.Cars = cars;
            SerializerHelper serializerHelper = new SerializerHelper();
            serializerHelper.SerializeObject(@"temp.txt", carsList);
            carsList = serializerHelper.DeserializeObject(@"temp.txt");
            cars = carsList.Cars;
        }

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對it145.com的支援。如果你想了解更多相關內容請檢視下面相關連結


IT145.com E-mail:sddin#qq.com