Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
608 views
in Technique[技术] by (71.8m points)

.net - Difference between NonSerialized and Xml.Serialization.XmlIgnore?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...