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

當涉及到跨進程甚至是跨域傳輸數據的時候,我們需要把對象序列化和反序列化。

首先可以使用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;
        }

以上就是這篇文章的全部內容瞭,希望本文的內容對大傢的學習或者工作具有一定的參考學習價值,謝謝大傢對WalkonNet的支持。如果你想瞭解更多相關內容請查看下面相關鏈接

推薦閱讀: