我写了这个方法,以便将xml字符串转换为对象:
private object Deserializer(Type type) { object instance = null; try { XmlSerializer xmlSerializer = new XmlSerializer(type); using (StringReader stringreader = new StringReader(somestring)) { instance = (type)xmlSerializer.Deserialize(stringreader); } } catch (Exception ex) { throw ex; } return instance; }
但在这里:
instance = (type)xmlSerializer.Deserialize(stringreader);
此错误显示:找不到类型或命名空间名称'type'(您是否缺少using指令或程序集引用?)我该如何解决?
你不能强制转换为"类型"你需要指定这样的确切类型(对于字符串):
(string)xmlSerializer.Deserialize(stringreader);
也许考虑使用这样的泛型函数:
private T Deserializer() { T instance = null; try { var xmlSerializer = new XmlSerializer(typeof(T)); using (var stringreader = new StringReader(somestring)) { instance = (T)xmlSerializer.Deserialize(stringreader); } } catch (Exception ex) { throw ex; } return instance; }
而不是像这样调用函数:
var instance = xmlSerializer.Deserialize();
如果要仅在运行时指定类型,可以使用:
instance = Convert.ChangeType(xmlSerializer.Deserialize(stringreader), type);