Home >Backend Development >C++ >How Can I Serialize a List of Abstract Base Class's Derived Types Using XmlSerializer?

How Can I Serialize a List of Abstract Base Class's Derived Types Using XmlSerializer?

Linda Hamilton
Linda HamiltonOriginal
2025-01-11 09:47:42961browse

How Can I Serialize a List of Abstract Base Class's Derived Types Using XmlSerializer?

Use XmlSerializer to serialize derived classes

Serializing objects containing abstract base class generic lists can present challenges when using XmlSerializer. This article explores how to solve this problem.

Question:

An object containing a list of derived classes (List), where the derived class is abstract and may cause an InvalidOperationException during the deserialization process.

Solution:

In order to successfully serialize a derived object, three methods can be used:

  1. Use [XmlInclude]: This attribute allows you to specify derived types to include when serializing. Suitable for situations where the number of derived types is small.
  2. Using XmlElement/XmlArrayItem: These properties allow you to directly specify the derived type associated with the property. More suitable for situations where the number of derived types is large.

Code example:

The following code demonstrates three methods:

<code class="language-csharp">using System;
using System.Collections.Generic;
using System.Xml.Serialization;

// 方法一:使用 [XmlInclude]
[XmlInclude(typeof(ChildA))]
[XmlInclude(typeof(ChildB))]
public abstract class ChildClass {
    public string ChildProp { get; set; }
}

// 方法二:使用 XmlElement
public class MyWrapper {
    [XmlElement("ChildA", Type = typeof(ChildA))]
    [XmlElement("ChildB", Type = typeof(ChildB))]
    public List<ChildClass> Data { get; set; }
}

// 方法三:使用 XmlArrayItem
public class MyWrapper2 {
    [XmlArrayItem("ChildA", Type = typeof(ChildA))]
    [XmlArrayItem("ChildB", Type = typeof(ChildB))]
    public List<ChildClass> Data { get; set; }
}

public class ChildA : ChildClass {
    public string AProp { get; set; }
}

public class ChildB : ChildClass {
    public string BProp { get; set; }
}</code>

By uncommenting the required attribute pairs, you can choose the solution that best suits your needs.

The above is the detailed content of How Can I Serialize a List of Abstract Base Class's Derived Types Using XmlSerializer?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn