NonSerialized 和 Xml.Serialization.XmlIgnore 之间的区别?

编程入门 行业动态 更新时间:2024-10-20 16:30:49
本文介绍了NonSerialized 和 Xml.Serialization.XmlIgnore 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们正在从 XML 中序列化/反序列化一个类,但是我们想要排除该类中的一些属性和字段.

System.NonSerialized 和 System.Xml.Serialization.XmlIgnore 属性似乎可以完成这项工作,但它们之间有什么区别?看来我们可以在类的属性或字段上使用 XmlIgnore.但是 NonSerialized 只能用于字段.是否有任何理由不在每种情况下都使用 XmlIgnore,如果是,NonSerialized 属性的用途是什么以及为什么使用方式不同?

这是允许的:

<System.NonSerialized()>_公共 Foo 作为字符串

这是允许的:

<System.Xml.Serialization.XmlIgnore()>_公共 Foo 作为字符串

这是允许的:

<System.Xml.Serialization.XmlIgnore()>_公共属性 Bar() 作为字符串得到返回_Bar结束获取设置(ByVal 值作为字符串)_Bar = 值结束集结束属性

但这是不允许的:

<System.NonSerialized()>_公共属性 Bar() 作为字符串得到返回_Bar结束获取设置(ByVal 值作为字符串)_Bar = 值结束集结束属性

解决方案

NonSerialized 适用于比 XML 更多类型的序列化.如果要序列化为二进制或 SOAP,则使用 NonSerialized;如果使用 XmlSerializer 严格序列化为 XML,则使用 XmlIgnore.请参阅 MSDN 上 NonSerializedAttribute 类的备注部分.p>

We're serializing/deserializing a class from XML but there are properties and fields in the class which we want to exclude.

The System.NonSerialized and System.Xml.Serialization.XmlIgnore attributes seem to do the job but what's the difference between them? It seems we can use XmlIgnore on either properties or fields of the class. But NonSerialized can only be used on fields. Is there any reason not to use XmlIgnore in every case, and if so what's the purpose of the NonSerialized attribute and why the difference in usage?

This is allowed:

<System.NonSerialized()> _ Public Foo As String

This is allowed:

<System.Xml.Serialization.XmlIgnore()> _ Public Foo As String

This is allowed:

<System.Xml.Serialization.XmlIgnore()> _ Public Property Bar() As String Get Return _Bar End Get Set(ByVal value As String) _Bar = value End Set End Property

But this is not allowed:

<System.NonSerialized()> _ Public Property Bar() As String Get Return _Bar End Get Set(ByVal value As String) _Bar = value End Set End Property

解决方案

NonSerialized applies to more types of serialization than XML. You would use NonSerialized if you were serializing to binary or SOAP, and XmlIgnore if you were strictly serializing to XML using an XmlSerializer. See the remarks section of the NonSerializedAttribute class at MSDN.

更多推荐

NonSerialized 和 Xml.Serialization.XmlIgnore 之间的区别?

本文发布于:2023-11-11 22:56:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579778.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   Xml   NonSerialized   XmlIgnore   Serialization

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!