DataContractSerializer: How to serialize classes/members without DataContract/DataMember attributes

后端 未结 3 1152
有刺的猬
有刺的猬 2020-12-16 03:36

DataContractSerializer requires classes and members to be marked with the DataContract and DataMember attributes. However, in my case

相关标签:
3条回答
  • 2020-12-16 04:24

    Just mark the class with the [Serializable] attribute. Any members you don't want serialized mark with [NonSerialized]. Note that [Serializable] causes all fields to be serialized by default, where [DataContract] serialized no fields by default except those marked with [DataMember].

    0 讨论(0)
  • 2020-12-16 04:35

    You cannot - plain and simple. The attribute are needed for the DataContractSerializer to pick up which elements to serialize. In contract to the XmlSerializer, which basically just serializes everything (unless you explicitly tell it to ignore it), the DataContractSerializer is "opt-in" - you have to explicitly tell it (by means of the attributes) which fields and/or properties to serialize.

    UPDATE: As several folks have pointed out, with .NET 3.5 SP1, Microsoft loosened those rules up a bit - any public read/write property will be serialized automatically by the DataContractSerializer. At the same time, your class also needs to have a parameterless default constructor - sounds like the exact requirements we had for XmlSerializer way back when....

    Of course, this:

    • doesn't allow you to serialize something private - if you want to serialize it, you have to expose it as public read/write property
    • doesn't allow you to specify a defined chosen ordering of the parameters - it will just use them in the order they appear in the class
    • now requires you to have a parameterless constructor in your class again for deserialization

    I still think these thing ought to be explicit and clear, making those no longer required opens up the path for lazy/sloppy programming - I don't like it. But if you want to, you can use it now without explicitly marking your properties with [DataMember].....

    Marc

    0 讨论(0)
  • 2020-12-16 04:36

    I believe it is possible. If you implement the ISerializable interface then the serializer users your implementation instead of the attributes. Although I think you will still have to mark the class [Serializable].

    Its a little more work than adding attributes but it does work.

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