C# 没有 [DataMember] 属性与具有 [IgnoreDataMember] 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19976281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:17:30  来源:igfitidea点击:

Not having a [DataMember] attribute vs having the [IgnoreDataMember] attribute

c#wcf

提问by David Pilkington

So i have been going through our code base and I have seen some our DTO's have a mix and match of [DataMember]and [IgnoreDataMember]attributes.

所以我一直在浏览我们的代码库,我看到我们的一些 DTO 具有[DataMember][IgnoreDataMember]属性的混合和匹配。

IN the past, we have been told that if we do not want something in the DTO serialised, simply do not add the [DataMember]attribute. Then I saw the other attribute and did some digging and it seems that this explicitly states that the property will not be serialised.

过去,我们被告知如果我们不想序列化 DTO 中的某些内容,只需不要添加该[DataMember]属性。然后我看到了另一个属性并进行了一些挖掘,这似乎明确指出该属性不会被序列化。

Now my question is, which is better? Adding [IgnoreDataMember]or not adding anything.

现在我的问题是,哪个更好?添加 [IgnoreDataMember]或不添加任何内容。

I have asked around and it seems that [IgnoreDataMember]is from the days when everything was serialised and you had to dictate what should be ignored (I believe in .Net 2). Then they changed it to the reverse and you had to explicitly state what SHOULD be serialised. Now it seems that you can do both.

我四处询问,似乎[IgnoreDataMember]是从所有内容都被序列化的日子开始,您必须决定应该忽略什么(我相信 .Net 2)。然后他们把它改成相反的,你必须明确说明应该序列化的内容。现在看来你可以做到这两点。

采纳答案by Marc Gravell

I have asked around and it seems that [IgnoreDataMember] is from the days when everything was serialised and you had to dictate what should be ignored (I believe in .Net 2). Then they changed it to the reverse and you had to explicitly state what SHOULD be serialised.

我四处询问,似乎 [IgnoreDataMember] 是从一切都被序列化的日子开始的,你必须规定应该忽略什么(我相信 .Net 2)。然后他们把它改成相反的,你必须明确说明应该序列化的内容。

Actually that's not quite true; IIRC it has always been both:

实际上这并不完全正确。IIRC 它一直都是:

  • if it is marked as [DataContract], then only the members marked [DataMember]are considered
  • if it is notmarked as [DataContract], then it defaults to everything, but you can subtractmembers using [IgnoreDataMember]
  • 如果标记为 [DataContract],则仅[DataMember]考虑标记的成员
  • 如果标记为[DataContract],则默认为所有内容,但您可以使用减去成员[IgnoreDataMember]

I usually just omit the [DataMember]of things that I don't want serialized, but in many ways [IgnoreDataMember]is more explicit - mainly for the benefit of the maintainer. It says "I am intentionally not serializing this", rather than "maybe I know that this isn't being serialized, but maybe I just forgot to add the attribute".

我通常只是省略[DataMember]我不想序列化的东西,但在很多方面[IgnoreDataMember]更明确 - 主要是为了维护者的利益。它说“我故意不序列化这个”,而不是“也许我知道这没有被序列化,但也许我只是忘记添加属性”。

Either will work.

要么会起作用。