我知道这个问题已经被问过了,但是我有一个奇怪的问题,我不知道该怎么做:
public static class XmlHelper
{
public static T Deserialize<T>(string xml)
{
using (var sr = new StringReader(xml))
{
var xs = new XmlSerializer(typeof(T));
return (T)xs.Deserialize(sr);
}
}
public static string Serialize(object o)
{
using (var sw = new StringWriter())
{
using (var xw = XmlWriter.Create(sw))
{
var xs = new XmlSerializer(o.GetType());
xs.Serialize(xw, o);
return sw.ToString();
}
}
}
}
[Serializable]
public class MyClass
{
public string Property1 {get;set;}
public int Property2 {get;set;}
}
我正在序列化课程:
var a = XmlHelper.Serialize(new MyClass{ Property1 = "a", Property2 = 3 });
var b = XmlHelper.Deserialize<object>(a);
错误:XML 文档 (1, 41) 中存在错误。
编辑:我想反序列化一个 as 对象,有可能吗?