将Type传递给方法以填充对象

时间:2017-04-17 20:06:29

标签: c# xml methods types

我无法弄清楚如何将类型传递给方法并获取对象的值。我在这里有一段代码写入xml文件:

        XmlSerializer xmlSerializer = new XmlSerializer(typeof(MG_GameData));
        FileStream fileStream = new FileStream (Application.dataPath + "/Data/MG_Data.data", FileMode.Open);
        //load the data into our temp object
        mg_GameDataTemp = xmlSerializer.Deserialize (fileStream) as MG_GameData;
        //close file
        fileStream.Close ();

我正在尝试将其重新编写为一种方法,但我不知道如何实际执行此操作:

public class XML { 

public static object open(Type type, string path) { 
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(MG_GameData));
    FileStream fileStream = new FileStream (path, FileMode.Open);
    object TempObject = xmlSerializer.Deserialize (fileStream) as type;
    fileStream.Close ();
    return TempObject;
}

public static void save() {

}
}

原因在于这行代码:

object TempObject = xmlSerializer.Deserialize (fileStream) as type;

您无法在那里传递值'type'。

我想知道为什么会这样,以及如何修复此方法以使其正常工作......

1 个答案:

答案 0 :(得分:1)

您可以使用通用方法传入类型:

public static T open<T>(string path) where T : class {
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
    using (FileStream fileStream = new FileStream(path, FileMode.Open)) {
        return (T)xmlSerializer.Deserialize(fileStream);
    }
}

您可以这样称呼它:

var data = open<MG_GameData>("data.xml");

您可以在网络上找到很多关于泛型的内容,例如this official programming guide from Microsoft