有没有办法在C#中使用内部setter序列化属性?
我知道这可能有问题 - 但如果有办法 - 我想知道.
例:
[Serializable] public class Person { public int ID { get; internal set; } public string Name { get; set; } public int Age { get; set; } }
序列化类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:\test.xml"); serializer.Serialize(writer, person); writer.Close();
结果(缺少ID属性):
Patrik 27
Marc Gravell.. 54
如果是一个选项,DataContractSerializer
(.NET 3.0)可以序列化非公共属性:
[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(); }
使用xml(重新格式化):
27 1 Patrik
Darin Dimitr.. 5
你可以实现IXmlSerializable,遗憾的是这否定了XmlSerializer最重要的好处(声明性地控制序列化的能力).DataContractSerializer(基于xml)和BinaryFormatter(基于二进制)可以用作XmlSerializer的替代品,每个都有其优点和缺点.
如果是一个选项,DataContractSerializer
(.NET 3.0)可以序列化非公共属性:
[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(); }
使用xml(重新格式化):
27 1 Patrik
你可以实现IXmlSerializable,遗憾的是这否定了XmlSerializer最重要的好处(声明性地控制序列化的能力).DataContractSerializer(基于xml)和BinaryFormatter(基于二进制)可以用作XmlSerializer的替代品,每个都有其优点和缺点.