I have a class that I instantiate to save or load xml data.
For example:
serilizer = new ObjectSerializer();
npcEntityData = serilizer.LoadNPCData(fileName);
goes to:
namespace TDIYCSharpLib
{
public class ObjectSerializer
{
NPCBaseInfo NPC;
MonsterBaseInfo monster;
public void SaveNPCData(object objGraph, string fileName)
{
XmlSerializer xmlFormat = new XmlSerializer(typeof(NPCBaseInfo));
using(Stream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
xmlFormat.Serialize(fileStream, objGraph);
}
}
public NPCBaseInfo LoadNPCData(string fileName)
{
XmlSerializer xmlDeformat = new XmlSerializer(typeof(NPCBaseInfo));
using (StreamReader fileStream = new StreamReader(fileName))
{
NPC = (NPCBaseInfo)xmlDeformat.Deserialize(fileStream);
}
return NPC;
}
}
}
This works as it is written; however, XmlSerializer’s need for typeof(SomeClass) means I have to provide this class with all of the possible classes that may need it as well as two specific methods to manipulate the data.
Like:
public void SaveMonsterData(object objGraph, string fileName)
{
XmlSerializer xmlFormat = new XmlSerializer(typeof(MonsterBaseInfo));
using (Stream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
xmlFormat.Serialize(fileStream, objGraph);
}
}
It is doable and is just some simple copy and pasting, but seems like a lot of unnecessary work.
You can use generic methods, e.g.
If you had a class called Npc, you would use the method like this: