我有一个简单的序列化类,用于将我的自定义对象写入磁盘上的XML:
public class ReaderWriter
{
public static void StoreObjectInformationInFile<T>(T objectToBeWritten, string passedDestinationFileName)
{
XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(objectToBeWritten.GetType());
TextWriter writer = new StreamWriter(passedDestinationFileName);
serializer.Serialize(writer, objectToBeWritten);
writer.Close();
}
}
有没有办法在这个类中添加一个通用的反序列化函数,它可以反过来做同样的事情?像这样的东西:
public static <T> GetObjectInformationFromFile<T>(string passedDestinationFileName)
{
...
}
答案 0 :(得分:2)
这是通用反序列化方法的原型
public static T GetObjectInformationFromFile<T>(string passedDestinationFileName)
{
var serializer = new XmlSerializer(typeof(T));
using(var stream = new StreamReader(passedDestinationFileName))
{
return (T)serializer.Deserialize(stream);
}
}