What is the advantage of using DataContractAttribute over SerializableAttribute?
I have fo开发者_StackOverflow社区und that my WCF services work normally when the data types involved doesn't have the [DataContract]
, but the [Serializable]
instead.
But all the WCF tutorials shows the first one instead of the latter. Why?
DataContractAttribute gives you more control over what gets sent over the wire, so you can opt to only send the necessary fields of a given entity. Serializable uses platform serialization, which assumes .NET and the same (or similar) versions of the types on both ends of the wire- it (usually) serializes all the private members, state, etc. DCS is intended for a lightweight XML-ish representation that you can have some control over, and XmlSerializer is for an XML format that you can have very fine control over (attribute data, etc).
It's not enough to mark the class with [DataContract], you have to decorate the fields you want to be serialized with [DataMember] as well.
The Data Contract is an "opt in" model of serialization, where the XML serialzier is "opt out."
One advantage is that the DataContract serializer is much quicker than the old XmlSerializer.
Edit: The examples would show the [DataContract] attribute because it is the one that is designed for the DataContractSerializer that WCF uses.
精彩评论