我有一个从文件中返回对象的方法.xml(请不要介意资源使用和命名,这只是一个例子(
public static T FromXMLFile<T>(string filePath)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
FileStream fs = new FileStream(filePath, FileMode.Open);
XmlTextReader xmlTextReader = new XmlTextReader(fs);
if(xmlSerializer.CanDeserialize(xmlTextReader))
{
object tempObject = (T)xmlSerializer.Deserialize(xmlTextReader );
xmlTextReader.Close();
return (T)tempObject;
}
else
return default(T);
}
现在我想做同样的事情,但用字符串而不是文件。我想出了这样的东西(再次,简化的示例(
public static T FromString<T>(string inputString)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
T result;
try
{
using (TextReader reader = new StringReader(inputString))
{
result = (T)serializer.Deserialize(reader);
}
return result;
}
catch //temporary solution, finally should stick to .CanDeserialize(xmlTextReader) usage
{
return default(T);
}
}
我将如何使用.在这种情况下可以反序列化((?
不要使用 Deserialize(TextReader)
重载,而是从TextReader
创建一个XmlReader
,并将该XmlReader
用于Deserialize
和CanDeserialize
调用:
using (TextReader reader = new StringReader(inputString))
using (XmlReader xmlReader = XmlReader.Create(reader))
{
if (serializer.CanDeserialize(xmlReader))
{
result = (T)serializer.Deserialize(xmlReader);
}
}
此方法(包括读取和写入(还允许您提供额外的读取器/写入器设置,以便对 API 进行精细控制。