C# DataContract Attribute for Private Fields?

百般思念 提交于 2019-12-07 18:31:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!