我需要将一些对象存储为XML文件,以便保存数据并在以后加载。 我编码了这个,它对我有用:
public static Project Load(String file)
{
using (var stream = System.IO.File.OpenRead(file))
{
var serializer = new XmlSerializer(typeof(Project));
return serializer.Deserialize(stream) as Project;
}
}
public static void Save(Project p, String file)
{
using (var writer = new System.IO.StreamWriter(file))
{
var serializer = new XmlSerializer(p.GetType());
serializer.Serialize(writer, p);
writer.Flush();
}
}
现在,我需要使用其他类型的对象执行此操作,并且我并不真的想要为每个对象类复制/粘贴这些方法。
是否可以将对象类传递给方法并使这些方法对任何对象类都是通用的?
答案 0 :(得分:5)
我通常使用https://stackoverflow.com/a/271423/1315444中的这两种方法 希望这会有所帮助:D
/// <summary>Serializes an object of type T in to an xml string</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="obj">Object to serialize</param>
/// <returns>A string that represents Xml, empty otherwise</returns>
public static string XmlSerialize<T>(this T obj) where T : class, new()
{
if (obj == null) throw new ArgumentNullException("obj");
var serializer = new XmlSerializer(typeof(T));
using (var writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
/// <summary>Deserializes an xml string in to an object of Type T</summary>
/// <typeparam name="T">Any class type</typeparam>
/// <param name="xml">Xml as string to deserialize from</param>
/// <returns>A new object of type T is successful, null if failed</returns>
public static T XmlDeserialize<T>(this string xml) where T : class, new()
{
if (xml == null) throw new ArgumentNullException("xml");
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(xml))
{
try { return (T)serializer.Deserialize(reader); }
catch { return null; } // Could not be deserialized to this type.
}
}
那么你可以选择
Project p = new Project();
string result = p.XmlSerialize();
Project p2 = result.XmlDeserialize<Project>();