C# 用xml序列化泛型类';s泛型类型
我需要将包含类型为C# 用xml序列化泛型类';s泛型类型,c#,.net,xml,generics,xml-serialization,C#,.net,Xml,Generics,Xml Serialization,我需要将包含类型为Pair的对象的列表序列化为xml。除了这些值,我还需要序列化它的泛型类型(类型T和U) 首先,我创建了一个类PairList来保存这些对的列表,然后我创建了一个实际的类,它表示一对两个值,key和value [XmlRoot("pairList")] public class PairList<T,U>{ [XmlElement("element")] public List<Pair<
Pair
的对象的列表序列化为xml。除了这些值,我还需要序列化它的泛型类型(类型T
和U
)
首先,我创建了一个类PairList来保存这些对的列表,然后我创建了一个实际的类,它表示一对两个值,key和value
[XmlRoot("pairList")]
public class PairList<T,U>{
[XmlElement("element")]
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;
[XmlAttribute("T-Type")]
public Type ttype;
[XmlAttribute("U-Type")]
public Type utype;
public Pair()
{
}
public Pair(T t, U u)
{
key = t;
value = u;
ttype = typeof(T);
utype = typeof(U);
}
}
[XmlRoot(“pairList”)]
公共类成对列表{
[XmlElement(“元素”)]
公开名单;
公共成对列表()
{
列表=新列表();
}
}
公共类对
{
[XmlAttribute(“键”)]
公钥;
[XmlAttribute(“值”)]
公共价值观;
[XmlAttribute(“T型”)]
公共类型ttype;
[XmlAttribute(“U型”)]
公共类型utype;
公共对()
{
}
公共对(T,U)
{
key=t;
数值=u;
T类型=类型(T);
utype=类型(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);
}
PairList myList=new PairList();
添加(新的一对(“c”,2));
添加(新的一对(“c”,2));
添加(新的一对(“c”,2));
添加(新的一对(“c”,2));
尝试
{
XmlSerializer serializer=新的XmlSerializer(typeof(PairList));
TextWriter tw=newstreamwriter(“list.xml”);
serializer.Serialize(tw,myList);
tw.Close();
}
捕获(异常xe)
{
MessageBox.Show(xe.Message);
}
不幸的是,我遇到了一个异常:反映类型时出错:PairList[System.String,System.Int32]
。欢迎任何关于如何避免此异常并序列化类的想法
如果我选择不序列化ttype
和utype
字段(通过将它们设置为受保护或私有),则序列化工作正常。我不明白为什么它不想序列化类型
字段。将您的类更改为
public class Pair<T, U>
{
[XmlAttribute("key")]
public T key;
[XmlAttribute("value")]
public U value;
[XmlAttribute("T-Type")]
public string ttype;
[XmlAttribute("U-Type")]
public string utype;
public Pair()
{
}
public Pair(T t, U u)
{
key = t;
value = u;
ttype = typeof(T).ToString();
utype = typeof(U).ToString();
}
}
公共类对
{
[XmlAttribute(“键”)]
公钥;
[XmlAttribute(“值”)]
公共价值观;
[XmlAttribute(“T型”)]
公共字符串类型;
[XmlAttribute(“U型”)]
公共字符串类型;
公共对()
{
}
公共对(T,U)
{
key=t;
数值=u;
ttype=typeof(T).ToString();
utype=typeof(U).ToString();
}
}
它应该会起作用。不能使用Xmlserializer
对类型
进行序列化/反序列化(例如,假设T
是在外部程序集中定义的复杂对象,并且要反序列化的计算机上不存在此程序集)