zoukankan      html  css  js  c++  java
  • Version Tolerant Serialization

    Let's Start it By a sample of code.

    // Version 1 of the Address class.
    [Serializable]
    public class Address
    {
        public string Street;
        public string City;
    }
    // Version 2.0 of the Address class.
    [Serializable]
    public class Address
    {
        public string Street;
        public string City;
        // The older application ignores this data.
        public string CountryField;
    }

    Fields can be marked as optional by applying the OptionalFieldAttribute attribute to them. During deserialization, if the optional data is missing, the serialization engine ignores the absence and does not throw an exception. Thus, applications that expect older versions of a type can send data to applications that expect newer versions of the same type.

    The following example shows version 2.0 of the Address class with the CountryField field marked as optional. If an older application sends version 1 to a newer application that expects version 2.0, the absence of the data is ignored.

    [Serializable]
    public class Address
    {
        public string Street;
        public string City;
    
        [OptionalField]
        public string CountryField;
    }

    Serialization callbacks are a mechanism that provides hooks into the serialization/deserialization process at four points.

     
    AttributeWhen the Associated Method is CalledTypical Use

    OnDeserializingAttribute

    Before deserialization.*

    Initialize default values for optional fields.

    OnDeserializedAttribute

    After deserialization.

    Fix optional field values based on contents of other fields.

    OnSerializingAttribute

    Before serialization.

    Prepare for serialization. For example, create optional data structures.

    OnSerializedAttribute

    After serialization.

    Log serialization events.

    * This callback is invoked before the deserialization constructor, if one is present.

    [Serializable]
    public class Address
    {
        public string Street;
        public string City;
        [OptionalField]
        public string CountryField;
    
        [OnDeserializing]
        private void SetCountryRegionDefault (StreamingContext sc)
        {
            CountryField = "Japan";
        }
    }
  • 相关阅读:
    C++中的虚函数、重写与多态
    STL中_Rb_tree的探索
    C++11 新用法
    FJUTOJ-3682 LRU算法的实现2 (链表+哈希)
    Windows系统对拍程序
    FOJ-2013 A Short Problem (前缀和)
    HDU-2036 改革春风吹满地 (数学)
    Ubuntu下PostgreSQL的安装和简单操作
    Ubuntu,Linux下goldendict词典安装及配置
    搜狗输入法输入汉字时候选栏乱码
  • 原文地址:https://www.cnblogs.com/malaikuangren/p/2575476.html
Copyright © 2011-2022 走看看