3

我有这段代码:

private object DeserialiseFromXMLFile(string fileLocation, Type type)
{
    XmlSerializer serializer = new
        XmlSerializer(type);

    FileStream fs = new FileStream(fileLocation, FileMode.Open);
    XmlReader reader = new XmlTextReader(fs);
    return serializer.Deserialize(reader);
}

我想知道我是否使用泛型,因为我希望返回类型为 T

有谁知道这是否可能,或者这是最优雅的解决方案?

提前致谢

4

4 回答 4

6
private T DeserialiseFromXMLFile<T>(string fileLocation)
{
    XmlSerializer serializer = new
        XmlSerializer(typeof(T));

    FileStream fs = new FileStream(fileLocation, FileMode.Open);
    XmlReader reader = new XmlTextReader(fs);
    return (T)serializer.Deserialize(reader);
}

然后你可以这样称呼它:

User item = DeserialiseFromXMLFile<User>("myFile.xml");
于 2013-04-12T16:02:12.397 回答
1

你可以做:

private T DeserialiseFromXMLFile<T>(string fileLocation)
{
    XmlSerializer serializer = new
        XmlSerializer(typeof(T));

    FileStream fs = new FileStream(fileLocation, FileMode.Open);
    XmlReader reader = new XmlTextReader(fs);
    return (T)serializer.Deserialize(reader);
}

该类型的typeof(T)返回Type实例,T最后您将序列化程序返回的对象显式转换为T.

于 2013-04-12T16:02:21.337 回答
1
    private static T DeserialiseFromXMLFile<T>(string fileLocation)        {
        XmlSerializer serializer = new XmlSerializer(typeof(T));

        FileStream fs = new FileStream(fileLocation, FileMode.Open);
        XmlReader reader = new XmlTextReader(fs);

        return (T)serializer.Deserialize(reader);
    }
于 2013-04-12T16:03:05.407 回答
1

你在找这样的东西吗?

private T DeserialiseFromXMLFile<T>(string fileLocation)
{
    XmlSerializer serializer = new
        XmlSerializer(typeof(T));

    FileStream fs = new FileStream(fileLocation, FileMode.Open);
    XmlReader reader = new XmlTextReader(fs);
    return (T) serializer.Deserialize(reader);
}

那么用法是:

var foo = DeserialiseFromXMLFile<Foo>("Foo.xml");

如果您不喜欢Foo明确指定,可以将方法更改为

private void DeserialiseFromXMLFile<T>(string fileLocation, out T t)
{
    ...
    t = (T) serializer.Deserialize(reader);
}

你会称之为

Foo foo;
DeserialiseFromXMLFile("Foo.xml", out foo);

您的代码也可以使用using

private T DeserialiseFromXMLFile<T>(string fileLocation)
{
    var serializer = new XmlSerializer(typeof(T));

    using (var fs = new FileStream(fileLocation, FileMode.Open))
    {
       var reader = new XmlTextReader(fs);
       return (T) serializer.Deserialize(reader);
    }
}
于 2013-04-12T16:03:06.997 回答