Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Can an internal setter of a property be serialized?

Is there any way to serialize a property with an internal setter in C#?
I understand that this might be problematic - but if there is a way - I would like to know.

Example:

[Serializable]
public class Person
{
    public int ID { get; internal set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

Code that serializes an instance of the class Person:

Person person = new Person();
person.Age = 27;
person.Name = "Patrik";
person.ID = 1;

XmlSerializer serializer = new XmlSerializer(typeof(Person));
TextWriter writer = new StreamWriter(@"c:est.xml");
serializer.Serialize(writer, person);
writer.Close();

Result (missing the ID property):

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Patrik</Name>
  <Age>27</Age>
</Person>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If it is an option, DataContractSerializer (.NET 3.0) can serialize non-public properties:

[DataContract]
public class Person
{
    [DataMember]
    public int ID { get; internal set; }
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public int Age { get; set; }
}
...
static void Main()
{
    Person person = new Person();
    person.Age = 27;
    person.Name = "Patrik";
    person.ID = 1;

    DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
    XmlWriter writer = XmlWriter.Create(@"c:est.xml");
    serializer.WriteObject(writer, person);
    writer.Close();
}

With the xml (re-formatted):

<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://schemas.datacontract.org/2004/07/">
    <Age>27</Age>
    <ID>1</ID>
    <Name>Patrik</Name>
</Person>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...