将xml字符串反序列化为对象

时间:2015-08-04 07:11:32

标签: c#

我写了这个方法,以便将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指令或程序集引用?) 我该如何解决?

2 个答案:

答案 0 :(得分:7)

你无法投射到"键入"你需要指定这样的确切类型(对于字符串):

(string)xmlSerializer.Deserialize(stringreader);

也许考虑使用这样的通用函数:

private T Deserializer<T>()
{
    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<SomeType>();

如果只想在运行时指定类型,可以使用:

instance = Convert.ChangeType(xmlSerializer.Deserialize(stringreader), type);

答案 1 :(得分:2)

但什么是类型是你做的类或什么?

也许你想做:

private object Deserializer<T>(T type)

编辑试试这个:

private static T LoadData<T>() where T : new ()
    {
        using (var reader = new StreamReader(@_path))
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            return (T) xmlSerializer.Deserialize(reader);
        }

    }