我有以下方法来打开和反序列化XML文件:
private static object DeserializeFile(string fileName, Type type)
{
Stream openFile = TitleContainer.OpenStream(fileName);
XmlSerializer reader = new XmlSerializer(type);
return reader.Deserialize(openFile);
}
我多次使用它来打开包含不同对象的不同文件。目前我必须以以下方式使用它:
City gameCity = (City)DeserializeFile(GameData.CITIES_FILE, typeof(City));
我有一种感觉,可以通过使方法返回一个作为参数传递给类型的对象来避免类型转换。谢谢
解决方案实际上非常简单:
private static T DeserializeFile<T>(string fileName)
{
Stream openFile = TitleContainer.OpenStream(fileName);
XmlSerializer reader = new XmlSerializer(typeof(T));
return (T)reader.Deserialize(openFile);
}
用法:
City gameCity = DeserializeFile<City>(GameData.CITIES_FILE);