问题
I'm testing XML Serialization in my class, but i noticed that the ID number didn't get saved when i ran the program.
So i was looking around and modifying a few things but nothing worked, then i saw that all fields except ID had both get and set properties. So i added a set; property to my ID number and poof it worked. The question is, does it have to be set; and get; function on all my properties for XML Serialization to work?
I don't want the ID number to be modified after the object has been created (its automatically generated).
回答1:
Yes, this is basically a restriction of XML serialization. From the XML Serialization docs:
Only public properties and fields can be serialized. Properties must have public accessors (get and set methods). If you must serialize non-public data, use the BinaryFormatter class rather than XML serialization.
XML serialization isn't as flexible as one might like.
回答2:
Note that if you want to serialize non-public data as xml, DataContractSerializer
might be useful. It isn't as flexible as XmlSerializer
(and you can't specify attributes), but it can serialize non-public data:
[DataContract]
public class Person {
[DataMember]
private int id;
public int Id {get {return id;}} // immutable
public Person(int id) { this.id = id; }
[DataMember]
public string Name {get;set;} // mutable
}
Note also that it doesn't use your constructor... or indeed any constructor - it cheats, allowing it to create an object and fill the data in afterwards.
来源:https://stackoverflow.com/questions/1154793/does-xml-serialization-require-properties-to-be-read-write