泛型可以用来返回实际对象吗?

时间:2013-04-12 15:59:38

标签: c# generics

我有这段代码:

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 个答案:

答案 0 :(得分: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");

答案 1 :(得分: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

答案 2 :(得分: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);
    }

答案 3 :(得分: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);
    }
}