Reputation: 3442
I need to serialize to xml a list containing objects of type Pair<T,U>
.
First, I've created a class PairList
to hold the list of the pairs and then I've created the actual class which represents a pair of two values, key
and value
.
[XmlRoot("pairList")]
public class PairList<T,U>
{
[XmlElement("list")]
public List<Pair<T,U>> list;
public PairList()
{
list = new List<Pair<T, U>>();
}
}
public class Pair<T, U>
{
[XmlAttribute("key")]
public T key;
[XmlAttribute("value")]
public U value;
public Pair(T t, U u)
{
key = t;
value = u;
}
}
Then, I tried serializing it:
PairList<string,int> myList = new PairList<string,int>();
myList.list.Add(new Pair<string, int>("c", 2));
myList.list.Add(new Pair<string, int>("c", 2));
myList.list.Add(new Pair<string, int>("c", 2));
myList.list.Add(new Pair<string, int>("c", 2));
try
{
XmlSerializer serializer = new XmlSerializer(typeof(PairList<string, int>));
TextWriter tw = new StreamWriter("list.xml");
serializer.Serialize(tw, myList);
tw.Close();
}
catch (Exception xe)
{
MessageBox.Show(xe.Message);
}
Unfortunately I am getting an exception: There was an error reflecting type: PairList[System.String,System.Int32]
. Any ideas on how I could avoid this exception and serialize the list are welcome.
Upvotes: 0
Views: 127
Reputation: 35363
Just add a parameterless constructor to your Pair<T, U>
class and it will work...
public Pair()
{
}
Upvotes: 1