如何序列化的接口,如IList的< T> [英] How to serialize an interface such as IList<T>
问题描述
可能重复:结果
的如何序列化一个IList< T> ;?
我希望序列化类(姑且称之为取值
),其中包含的IList<类型的属性; T>
,其中 T
是我所定义的另一个类。我得到一个例外,当我试图序列化类取值
的一个实例为XML。这是可以理解的的XmlSerializer
不知道用哪个具体的类。有没有一种方法,希望使用属性,指定序列化/反序列化实例时实例化哪个具体的类。我班取值
实施创建列表℃的情况下,T>
类。下面是一些代码来说明我的例子:
I wish to serialize an class (let's call it S
) that contains a property of the type IList<T>
where T
is another class which I have defined. I get an exception when I attempted to serialize an instance of class S
to XML. This is understandable as the XmlSerializer
doesn't know which concrete class to use. Is there a way, hopefully using attributes, to specify which concrete class to instantiate when serializing/deserializing an instance. My implementation of class S
creates a instance of the List<T>
class. Here is some code to illustrate my example:
using System;
using System.Xml.Serialization;
using System.IO;
[Serializable]
public class T { }
[Serializable]
public class S
{
public IList<T> ListOfTs { get; set; }
public S()
{
ListOfTs = new List<T>();
}
}
public class Program
{
public void Main()
{
S s = new S();
s.ListOfTs.Add(new T());
s.ListOfTs.Add(new T());
XmlSerializer serializer = new XmlSerializer(typeof(S));
serializer.Serialize(new StringWriter(), s);
}
}
我希望有一个属性,我可以在上面放置在 ListOfTs
定义,以连载说,假设的实例名单< T>
序列化/反序列化时。
I'm hoping there's an attribute I can place above the ListOfTs
definition that says to the serialize, "assume an instance of List<T>
when serializing/deserializing".
推荐答案
更改
public IList<T> ListOfTs { get; set; }
到
to
public List<T> ListOfTs { get; set; }
然后,它会正常工作。
Then it will work.
这篇关于如何序列化的接口,如IList的< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!