私有字段的 C# DataContract 属性?

发布于 2024-12-27 07:23:00 字数 570 浏览 0 评论 0原文

对于标有属性[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷离° 2025-01-03 07:23:00

不,您似乎没有正确阅读文档。

数据契约是一种公开共享信息的方式,与常规序列化略有不同。

从您链接的文档页面:

然后必须将 DataMemberAttribute 属性应用于数据协定类型的每个成员,以指示它是数据成员,即它应该被序列化。

但这仅适用于像您一样添加 [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:

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.

惟欲睡 2025-01-03 07:23:00

有趣的是,链接说:

默认情况下,DataContractSerializer 推断数据协定并序列化所有公开可见的类型。该类型的所有公共读/写属性和字段都被序列化。

在我的应用程序中,我发现只有包含 [DataMember] 的属性才会被序列化。具有公共 getter/setter 的公共属性不会被序列化,除非我专门将 [Datamember] 放在它们上。


为了解决您的具体问题,我将用 [DataMember] 标记所有 3 个字段,并且 complexType 类也应该标记为 [DataContract]

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].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文