-2

我知道这个问题已经被问过了,但是我有一个奇怪的问题,我不知道该怎么做:

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 对象,有可能吗?

4

1 回答 1

1

您没有传递正确的序列化类型,请将代码更改为:

public static string Serialize<T>(T o)
{
    using (var sw = new StringWriter())
    {
        using (var xw = XmlWriter.Create(sw))
        {
            var xs = new XmlSerializer(typeof(T));
            xs.Serialize(xw, o);
            return sw.ToString();
        }
    }
}
...
// we don't need to explicitly define MyClass as the type, it's inferred
var a = XmlHelper.Serialize(new MyClass{ Property1 = "a", Property2 = 3 });
var b = XmlHelper.Deserialize<MyClass>(a);
于 2013-01-11T14:20:53.307 回答