在使用XmlSerializer进行XML序列化时,处理包含派生自抽象类的泛型列表的对象可能会遇到挑战。尝试反序列化此类对象可能会导致InvalidOperationException异常。
为了解决这个问题,您可以使用以下三种方法之一:
1. 在基类型上使用[XmlInclude]特性:
<code class="language-csharp">using System.Xml.Serialization; [XmlInclude(typeof(ChildA))] [XmlInclude(typeof(ChildB))] public abstract class ChildClass { public string ChildProp { get; set; } }</code>
2. 在属性上使用[XmlElement]特性:
<code class="language-csharp">public class MyWrapper { [XmlElement("A", Type = typeof(ChildA))] [XmlElement("B", Type = typeof(ChildB))] public List<ChildClass> Data { get; set; } }</code>
3. 在属性上使用[XmlArrayItem]特性:
<code class="language-csharp">public class MyWrapper { [XmlArrayItem("A", Type = typeof(ChildA))] [XmlArrayItem("B", Type = typeof(ChildB))] public List<ChildClass> Data { get; set; } }</code>
根据您的具体需求取消相应属性对的注释。 通过使用这些方法之一,XmlSerializer将能够在序列化和反序列化期间处理派生类。
以上是如何使用 XmlSerializer 序列化通用列表中的派生类?的详细内容。更多信息请关注PHP中文网其他相关文章!