WCF DataContract serialization of read-only properties?

前端 未结 2 1716
温柔的废话
温柔的废话 2020-12-31 06:48

Whenever I use WCF, I always try to make immutable classes that end up going over the wire (i.e. parameters set in constructor, properties are read-only). However, this gets

相关标签:
2条回答
  • 2020-12-31 07:09

    To ensure both immutability and easy implementation at the same time add a private setter for the property to serve deserialization. A lot happens under the bonnet, but it works.

    0 讨论(0)
  • 2020-12-31 07:27

    If you use the DataContractSerializer (which is the default for WCF), you can serialize anyhting that's decorated with the [DataMember] attribute - even a read-only field:

    [DataContract]
    public class VirtualMachineTemplate : VirtualMachineTemplateBase, IXmlPicklable, IEnableLogger
    {
        [DataMember]
        ulong _SizeInBytes;
    }
    

    But you need to use the DataContractSerializer - not the XML serializer. The XML serializer can ONLY serialize public properties (and it will, unless you put a [XmlIgnore] on them).

    The DataContractSerializer is different:

    • it doesn't need a parameter-less default constructor
    • it will only serialize what you explicitly mark with [DataMember]
    • but that can be anything - a field, a property, and of any visibility (private, protected, public)
    • it's a bit faster than XmlSerializer, but you don't get a lot of control over the shape of the XML - you only get a say in what's included

    See this blog post and this blog post for a few more tips and tricks.

    Marc

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