I've a question regarding serialization using C#. When I try te serialize my object called "rl", it just backup the list's objects but not main variables "reference" and "Description". I don't undestand what i have to do to correct it. My workaround is to add variable List myVar into the main class and to not deravate from List. Thank you for your help.
Ludovic
My code is here:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
RegisterList rl = new RegisterList();
rl.Reference = "This is my ref";
rl.Description = "This is the description of register list";
rl.Add(new SingleRegister("name1", "data1"));
rl.Add(new SingleRegister("name2", "data2"));
LoadAndStore<RegisterList>.Save(rl, "dummy.txt");
}
}
[Serializable]
public class RegisterList: List<SingleRegister>
{
public string Reference;
public string Description;
}
[Serializable]
public class SingleRegister
{
public string Name;
public string Data;
public SingleRegister(string name, string data)
{
Name = name;
Data = data;
}
public SingleRegister() { }
}
public static class LoadAndStore<T>
{
public static void Save(T obj, string filename)
{
XmlSerializer bf = new XmlSerializer(typeof(T));
// Create a file with the specified filename
FileStream fs = new FileStream(filename, FileMode.Create);
// Serialize the provided object and output to filestream
bf.Serialize(fs, obj);
// Flush the filestream buffer and close
fs.Flush();
fs.Close();
}
public static T Restore(string filename)
{
// Create a default for value types or null for reference types
T e = default(T);
// if specified file doesn't exist, return
if (!File.Exists(filename))
return e;
XmlSerializer bf = new XmlSerializer(typeof(T));
// Open file
FileStream fs = new FileStream(filename, FileMode.Open);
// Deserialize file contents and cast to specified type
e = (T)bf.Deserialize(fs);
// Close the filestream
fs.Close();
return e;
}
}