问题
For a class marked with the attribute, [DataContract], does its private fields, which should be serialized, be marked as [DataMember]?
Example:
[DataContract]
public class Component
{
// [DataMember] is not needed since public fields get automatically serialized
public int number;
// do I need [DataMember] here?
private string characters;
// [DataMember] is required here, but I also need to include the
// attribute [DataMember] in this class's definition
private complexType cT;
I'm reading DataContractAttribute Class correctly, right?
回答1:
No, it doesn't look like you are reading the documentation correctly.
DataContracts are a way to publicly share information that is a little different than regular serialization.
From the documentation page you link:
The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized.
But that only applies if you add the [DataContract]
attribute like you did.
回答2:
Interesting that the link says:
By default, the DataContractSerializer infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized.
In my applications, I've found that only properties that include [DataMember]
get serialized. Public properties with public getters/setters do not get serialized unless I specifically put [Datamember]
on them.
To address your specific question, I would mark all 3 fields with [DataMember]
, and complexType
class should also be marked as a [DataContract]
.
来源:https://stackoverflow.com/questions/8883615/c-sharp-datacontract-attribute-for-private-fields