xml使用其泛型类型序列化泛型类 [英] xml serialize a generic class with it's generic types
问题描述
我需要将包含Pair<T,U>
类型的对象的列表序列化为xml.除了这些值,我还需要序列化其泛型的类型(T
和U
的类型).
I need to serialize to xml a list containing objects of type Pair<T,U>
. Along with those values, I would also need to serialize the type of it's generics(the type ofT
and U
).
首先,我创建了一个PairList类来保存对的列表,然后我创建了一个实际的类,该类代表一对两个值,键和值.
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("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);
}
}
然后,我尝试将其序列化:
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);
}
不幸的是,我遇到一个例外:There was an error reflecting type: PairList[System.String,System.Int32]
.欢迎提供关于如何避免此异常并序列化类的任何想法.
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 class are welcome.
如果我选择不对ttype
和utype
字段进行序列化(通过将它们设置为保护或私有),则序列化将起作用.我不知道为什么它不想序列化Type
字段.
If I choose not to serialize the ttype
and utype
fields(by making them protected or private) the serialization works. I can't figure out why it doesn't want to serialize the Type
fields.
推荐答案
将您的班级更改为
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();
}
}
,它应该可以工作.您不能使用Xmlserializer
序列化/反序列化Type
.(例如,假设T
是在外部程序集中定义的复杂对象,并且该程序集在您要反序列化的计算机上不存在)
and it should work. You can not serialize/deserialize Type
with Xmlserializer
.(For example, suppose T
is a complex object defined in an external assembly and this assembly does not exist on the computer where you want to deserialize)
这篇关于xml使用其泛型类型序列化泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!