Can an internal setter of a property be serialized?

前端 未结 6 972
盖世英雄少女心
盖世英雄少女心 2020-12-07 17:32

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.

6条回答
  •  臣服心动
    2020-12-07 18:06

    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:\test.xml");
        serializer.WriteObject(writer, person);
        writer.Close();
    }
    

    With the xml (re-formatted):

    
    
        27
        1
        Patrik
    
    

提交回复
热议问题