我想创建一个反序列化序列化类的方法。
代码:
Settings newSettings = new Settings(); //Settings is a class.
Settings lastSettings = new Settings();
private void LoadXML(Type type,string filepath)
{
XmlSerializer serializer = new XmlSerializer(type);
FileStream fs = File.Open(filepath,FileMode.Open);
Settings newset = (Settings)serializer.Deserialize(fs); //Deserializes a serializable class file.
newSettings = newset; //Sets these settings as NewSettings
lastSettings = newSettingsXML; //Before form opening, sets information into form.
fs.Close();
}
现在我想用方法做这些。我为“人”类创建了不同的方法。此方法从xml文件中读取人员并将这些人员设置为表单。
private void PersonFromXML(string filepath)
{
XmlSerializer serializer = new XmlSerializer(typeof(BindingList<Person>));
FileStream fs = File.Open(filepath,FileMode.Open);
BindingList<Person> XML_Person = (BindingList<Person>)serializer.Deserialize(fs);
NEW_XML_Person = XML_Person; // These are BindingList<Person>.
fs.Close();
Grid_Person.DataSource = XML_Person;
}
我想将这些反序列化方法作为一个不同的方法。我想将此方法写入dll文件。 我试着这样做:
private BindingList<Type> FromXML(BindingList<Type> type,string filepath)
{
XmlSerializer ser = new XmlSerializer(typeof(type));
FileStream fs = File.Open(filepath,FileMode.Open);
BindingList<Type> BL = (type)ser.Deserialize(fs);
fs.Close();
return BL;
}
但它没有用。因为我无法将BindingList类型设置为Person ..我该怎么办?感谢。
答案 0 :(得分:0)
似乎您忘记在方法声明中设置泛型类型参数。
试试这个:
public static class MySerializationHelper
{
public static class From
{
public TReturn XMLFile<TReturn>(string contents)
{
var serializer = new XmlSerializer(typeof(TReturn));
var fs = File.Open(filePath, FileMode.Open);
var result = (TReturn)serializer.Deserialize(fs);
fs.Close();
return result;
}
}
public static class To
{
public void XMLFile<TType>(TType object, string filePath)
{
// Serialize it here...
}
}
}
然而,您可以简单地使用它,例如:
var bindingList = MySerializationHelper.From.XmlFile<IBindingList<Person>>("Persons.xml");
var person = MySerializationHelper.From.XmlFile<Person>("Person_1.xml");
MySerializationHelper.To.XmlFile<IBindingList<Person>>(bindingList, "Persons_copy.xml");
MySerializationHelper.To.XmlFile<Person>(person, "Person_1_Copy.xml");