Combinando le due cose potete scrivere dei metodi per la serializzazione e deserializzazione di classi e renderli generici. Ad esempio:
Con i seguenti "Extension Method"
/// <summary> /// Serializes to XML. /// </summary> /// <param name="value">The object to serialize.</param> /// <returns> /// a XElement rappresenting the class serialization /// </returns> public static XElement SerializeToXML(this object value) { XmlSerializer x = new XmlSerializer(value.GetType()); XDocument doc = new XDocument(); using (XmlWriter xw = doc.CreateWriter()) { x.Serialize(xw, value); xw.Close(); } return doc.Root; } /// <summary> /// Deserializes the specified string to an object of type T. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value containing an xml.</param> /// <returns> /// an object of type T /// </returns> public static T Deserialize<T>(this string value) { XElement xElement = XElement.Parse(value); return xElement.Deserialize<T>(); } /// <summary> /// Deserializes the specified string to an object of type T. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value containing an xml.</param> /// <returns> /// an object of type T /// </returns> public static T Deserialize<T>(this XElement value) { XmlSerializer x = new XmlSerializer(typeof(T)); T result; using (XmlReader xr = value.CreateReader()) { result = (T)x.Deserialize(xr); xr.Close(); } return result; }
In questo modo, per serializzare una classe dovrete semplicemente scrivere
MyClass a = new MyClass();
XElement xml = a.SerializeToXML();
MyClass b = xml.Deserialize<MyClass>(xml)
Nessun commento:
Posta un commento