我正在尝试传入一个类型对象以传递给序列化程序。
internal void SerializeXML(Object ObjType, String XMLRoot, Object Output, String Filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(ObjType), new XmlRootAttribute(XMLRoot));
StreamReader reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(Filename));
Output = (Type)serializer.Deserialize(reader);
reader.Close();
}
我想通过它来调用它(Main.LanguageList.Language是一个类):
SerializeXML(Main.LanguageList.Language, "Language", LanguageListFile, InternalLangListXML);
我得到的Object是一个变量,但是用作一个类型。
答案 0 :(得分:2)
编写泛型方法会更优雅:
internal void DeserializeXML<T>(String XMLRoot, T Output, String Filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(XMLRoot));
StreamReader reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(Filename));
Output = (T)serializer.Deserialize(reader);
reader.Close();
}
并称之为:
DeserializeXML<Main.LanguageList.Language>("Language", LanguageListFile, InternalLangListXML);
此外,它建议更改方法以返回结果,而不是依赖于输出参数:
internal T DeserializeXML<T>(String XMLRoot, String Filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(XMLRoot));
using (StreamReader reader = new StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(Filename)))
{
return (T)serializer.Deserialize(reader);
}
}
然后可以这样调用:
var result = DeserializeXML<Main.LanguageList.Language>("Language", InternalLangListXML);