Programmatically set properties to exclude from serialization

前端 未结 7 1171
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 07:19

Is it possible to programmatically set that you want to exclude a property from serialization?

Example:

  • When de-serializing, I want to load up an ID fi
相关标签:
7条回答
  • 2020-12-30 07:39

    It depends on serialization type. Here full example for doing this with BinaryFormatter:

    You may use OnDeserializedAttribute:

    [Serializable]
    class SerializableEntity
    {
      [OnDeserialized]
      private void OnDeserialized()
      {
        id = RetrieveId();
      }
    
      private int RetrievId() {}
    
      [NonSerialized]
      private int id;
    }
    

    And there is another way to do this using IDeserializationCallback:

    [Serializable]
    class SerializableEntity: IDeserializationCallback 
    {
      void IDeserializationCallback.OnDeserialization(Object sender) 
      {
        id = RetrieveId();
      }
    
      private int RetrievId() {}
    
      [NonSerialized]
      private int id;
    }
    

    Also you may read great Jeffrey Richter's article about serialization: part 1 and part 2.

    0 讨论(0)
提交回复
热议问题