开发者

Programmatically set properties to exclude from serialization

开发者 https://www.devze.com 2023-01-02 20:48 出处:网络
Is it possible to programmatically set that you want to exclude a property from serialization? Example:

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

Example:

  • When de-serializing, I want to load up a开发者_运维知识库n ID field
  • When serializing, I want to NOT output the ID field


I believe there are three options here:

  1. Use XmlIgnore attribute. The downside is that you need to know in advance which properties you want the xmlserializer to ignore.

  2. Implement the IXmlSerializable interface. This gives you complete control on the output of XML, but you need to implement the read/write methods yourself.

  3. Implement the ICustomTypeDescriptor interface. I believe this will make your solution to work no matter what type of serialization you choose, but it is probably the lengthiest solution of all.

 


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.


If you are serializing to XML, you can use XMLIgnore

As in:

class SomeClass
{
  [XmlIgnore] int someID;
  public string someString;
}


An old post, but I found ShouldSerialize pattern http://msdn.microsoft.com/en-us/library/53b8022e%28VS.71%29.aspx That is really HELPFUL!!!


If you want to include field during serialization but ignore it during deserialization then you can use OnDeserializedAttribute to run a method which will set default value for ID field.


If you're using XML serialization, use the [XmlIgnore] attribute. Otherwise, how to ignore a particular property is defined by the serializer itself.


The NonSerializedAttribute attribute.

http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消