0

タイプ のオブジェクトを含むリストを xml にシリアル化する必要がありますPair<T,U>

最初にPairList、ペアのリストを保持するクラスを作成し、次に 2 つの値のペアを表す実際のクラスを作成しましkeyvalue

[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;
    }
}

次に、シリアル化してみました。

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);
}

残念ながら、例外が発生しています: There was an error reflecting type: PairList[System.String,System.Int32]。この例外を回避してリストをシリアル化する方法についてのアイデアは大歓迎です。

4

1 に答える 1