私有字段的 C# DataContract 属性?
对于标有属性[DataContract]的类,其应序列化的私有字段是否标记为[DataMember]?
示例:
[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;
我正在正确读取 DataContractAttribute Class,对吧?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,您似乎没有正确阅读文档。
数据契约是一种公开共享信息的方式,与常规序列化略有不同。
从您链接的文档页面:
但这仅适用于像您一样添加
[DataContract]
属性的情况。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:
But that only applies if you add the
[DataContract]
attribute like you did.有趣的是,链接说:
在我的应用程序中,我发现只有包含
[DataMember]
的属性才会被序列化。具有公共 getter/setter 的公共属性不会被序列化,除非我专门将[Datamember]
放在它们上。为了解决您的具体问题,我将用
[DataMember]
标记所有 3 个字段,并且complexType
类也应该标记为[DataContract]
。Interesting that the link says:
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]
, andcomplexType
class should also be marked as a[DataContract]
.