2014-06-18 50 views
0

我有寫我的自定義對象到XML磁盤上的一個簡單的序列化類:常規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) 
     { 
      ... 
     } 

回答

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); 
    } 
}