Programmatically set properties to exclude from serialization

前端 未结 7 1170
爱一瞬间的悲伤
爱一瞬间的悲伤 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:22

    If you are serializing to XML, you can use XMLIgnore

    As in:

    class SomeClass
    {
      [XmlIgnore] int someID;
      public string someString;
    }
    
    0 讨论(0)
  • 2020-12-30 07:26

    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.

    0 讨论(0)
  • 2020-12-30 07:26

    The NonSerializedAttribute attribute.

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

    0 讨论(0)
  • 2020-12-30 07:29

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

    0 讨论(0)
  • 2020-12-30 07:32

    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.

     

    0 讨论(0)
  • 2020-12-30 07:35

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

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