你在找这样的东西吗?
private T DeserialiseFromXMLFile<T>(string fileLocation)
{
XmlSerializer serializer = new
XmlSerializer(typeof(T));
FileStream fs = new FileStream(fileLocation, FileMode.Open);
XmlReader reader = new XmlTextReader(fs);
return (T) serializer.Deserialize(reader);
}
那么用法是:
var foo = DeserialiseFromXMLFile<Foo>("Foo.xml");
如果您不喜欢Foo
明确指定,可以将方法更改为
private void DeserialiseFromXMLFile<T>(string fileLocation, out T t)
{
...
t = (T) serializer.Deserialize(reader);
}
你会称之为
Foo foo;
DeserialiseFromXMLFile("Foo.xml", out foo);
您的代码也可以使用using
:
private T DeserialiseFromXMLFile<T>(string fileLocation)
{
var serializer = new XmlSerializer(typeof(T));
using (var fs = new FileStream(fileLocation, FileMode.Open))
{
var reader = new XmlTextReader(fs);
return (T) serializer.Deserialize(reader);
}
}