简体   繁体   English

将包含IList的对象序列化为XML

[英]Serialize to XML an object that contains IList

So I have an Object called FormType. 所以我有一个叫做FormType的对象。 It contains some strings, booleans etc. 它包含一些字符串,布尔值等。

But FormType also contains this: 但是FormType也包含以下内容:

   private IList<FormTypeVersion> _versions = new List<FormTypeVersion>();

    public virtual IList<FormTypeVersion> Versions
    {
        get { return _versions; }
        set { _versions = value; }
    }

Is this why I am getting this error: 这就是为什么我收到此错误的原因:

{"Cannot serialize member 'Domain.FormType.Versions' of type 'System.Collections.Generic.IList`1

Also - FormTypeVersion also contains some ILists. 另外-FormTypeVersion还包含一些ILists。

How can I get round this error, it happens at this line: 如何解决此错误,它发生在以下行:

var xm = new XmlSerializer(typeof(T));

The XmlSerializer cannot deserialize interfaces (unless you want to implement IXmlSerializable yourself on the FormType object). XmlSerializer无法反序列化接口(除非您想自己在FormType对象上实现IXmlSerializable)。 That is why you are seeing that exception. 这就是为什么您看到该异常。

If you change your IList to List it should work like in the following example: 如果将IList更改为List,则它应如以下示例所示工作:

[Serializable]
public class FormType
{
    private List<FormTypeVersion> _versions = new List<FormTypeVersion>();

    public virtual List<FormTypeVersion> Versions
    {
        get { return _versions; }
        set { _versions = value; }
    }
}

If you don't have the luxury to change your type from IList to List, then the cleanest approach is to implement IXmlSerializable . 如果您不愿意将类型从IList更改为List,那么最干净的方法是实现IXmlSerializable There are other solutions using abstract types, reflection and similar, but i wouldn't call that clean. 还有其他使用抽象类型,反射和类似类型的解决方案,但我不会称之为干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM