/// <summary> /// 通过反射实现具有只读属性的类的序列化 /// 类必私有变量必须是"_"+属性名称 /// </summary> public abstract class ReadOnlySerializable : IXmlSerializable { #region XmlSerializable /// <summary> /// /// </summary> /// <returns></returns> public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// /// </summary> /// <param name="reader"></param> public void ReadXml(System.Xml.XmlReader reader) { Type type = this.GetType(); reader.ReadStartElement(type.Name); while (reader.Read()) { if (reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (string.IsNullOrEmpty(reader.LocalName) == false) { FieldInfo field = type.GetField("_" + reader.LocalName, BindingFlags.NonPublic | BindingFlags.Instance); if (field != null) { if (field.FieldType == typeof(string) || field.FieldType.BaseType.Equals(typeof(System.ValueType))) { field.SetValue(this, Convert.ChangeType(reader.ReadString(), field.FieldType)); } else { reader.ReadStartElement(); XmlSerializer xs = new XmlSerializer(field.FieldType); field.SetValue(this, xs.Deserialize(reader)); reader.ReadEndElement(); } } } } else if (reader.NodeType == System.Xml.XmlNodeType.EndElement) { reader.ReadEndElement(); break; } } } /// <summary> /// /// </summary> /// <param name="writer"></param> public void WriteXml(System.Xml.XmlWriter writer) { foreach (var item in this.GetType().GetProperties()) { object value = item.GetValue(this, null); if (value != null) { if (item.PropertyType != typeof(string) && item.PropertyType.BaseType.Equals(typeof(System.ValueType)) == false) { writer.WriteStartElement(item.Name); XmlSerializer xs = new XmlSerializer(item.PropertyType); xs.Serialize(writer, value); writer.WriteEndElement(); } else { writer.WriteStartElement(item.Name); writer.WriteString(value.ToString()); writer.WriteEndElement(); } } } } #endregion }
![](https://img2024.cnblogs.com/blog/35695/202408/35695-20240826070647288-243310440.jpg)