如何防止自动实现的属性被序列化?
如何防止自动实现的属性被二进制格式化程序序列化? [NonSerialized] 属性只能与字段一起使用。当使用自动实现的属性时,该字段会被隐藏。
How can I prevent a auto implemented property from being serialized by the binary formatter?
The [NonSerialized] attribute can only be used with fields. And the field is hidden when using auto implemented properties.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
自动实现的属性不支持它。您必须使用支持字段并在其上设置 NonSerializedAttribute 。
It´s not supported for auto implemented properties. You have to use a backing field and set the NonSerializedAttribute on it.
但它似乎不适用于自动实现的属性。我认为这是值得一提的,因为知道何时序列化带有附加事件订阅者的对象非常有用。
But it doesn't seem to for auto-implemented properties. I thought it was worth mentioning because it's useful to know when serializing an object with event subscribers attached to it.
如果您要序列化为 Json 并使用 Json.NET 序列化器(我强烈推荐它,因为它具有比市场上的许多其他序列化器提供更多功能),然后您可以使用
[JsonIgnore]
在属性上实现您想要的结果。您不需要创建字段。
所以你的代码将是:
If you're serializing to Json and using the Json.NET serializer (which I'd highly recommend as it has a lot more to offer than a number of other serializers on the market) then you can achieve your desired outcome on properties using
[JsonIgnore]
.You don't need to create a field.
So your code would be:
如果要序列化为 Xml,则可以使用 XmlIgnore 属性。
If you are serializing to Xml then you can use XmlIgnore attribute.
我不确定你可以。这篇关于
SerializedAttribute
的 MSDN 文章建议您实现 ISerialized 并自己控制序列化:或者放弃该特定字段的自动属性。
I'm not sure you can. This MSDN article on
SerializableAttribute
suggests you implement ISerializable and control the serialisation yourself:Or switch away from an auto-property for that specific field.
自动实现的属性是不可能的。
考虑以下内容:
(http://social .msdn.microsoft.com/Forums/en-US/vcsharp2008prerelease/thread/2b6eb489-122a-4418-8759-10808252b195)
It's not possible for auto implemented properties.
Consider folowing:
(http://social.msdn.microsoft.com/Forums/en-US/vcsharp2008prerelease/thread/2b6eb489-122a-4418-8759-10808252b195)
建议的使用非序列化支持字段的解决方案似乎无法在 .NET 4.0 中正常运行(至少在 Xml 序列化的情况下)。该字段确实没有被序列化,但使用它的公共财产确实被序列化,从而达不到目的。使用 XmlIgnore 解决方法有助于解决 Xml 序列化问题。免责声明 - 我没有验证二进制序列化行为。
The proposed solution of using not-serialized backing field does not seem to function properly with .NET 4.0 (at least in the case of Xml serialization). The field indeed does not get serialized but public property that uses it does serialize and thus defeats the purpose. Using XmlIgnore workaround helps in case of Xml serialization. Disclaimer - I did not verify binary serialization behavior.