Home > Backend Development > C++ > How to Serialize Derived Classes within Generic Lists using XmlSerializer?

How to Serialize Derived Classes within Generic Lists using XmlSerializer?

Patricia Arquette
Release: 2025-01-11 10:42:45
Original
557 people have browsed it

How to Serialize Derived Classes within Generic Lists using XmlSerializer?

Use XmlSerializer to serialize derived classes

When using XmlSerializer to serialize an object containing a generic list of abstract class derived classes, users may encounter an InvalidOperationException exception during the deserialization process. Solving this problem requires specific techniques for handling the serialization of derived objects.

Solution

There are three effective methods:

  1. [XmlInclude] Attributes: Applies the [XmlInclude] attribute before the abstract class declaration, including each derived class type. This ensures that the serializer knows how to handle these specific derived types.
  2. XmlElement/XmlArrayItem Attributes: Use the [XmlElement] or [XmlArrayItem] attribute on an attribute containing a list. Specify the derived class type in these properties to instruct the serializer to recognize and deserialize the object.
  3. Combination of two methods: Combine these two methods by using [XmlInclude] on abstract classes and [XmlElement] or [XmlArrayItem] on properties, thus providing explicit and implicit Type handling.

The following code snippets provide detailed implementation examples using each method:

<code class="language-csharp">// 1: [XmlInclude(typeof(ChildA))]
// 1: [XmlInclude(typeof(ChildB))]
public abstract class ChildClass {
    public string ChildProp { get; set; }
}

// 2: [XmlElement("A", Type = typeof(ChildA))]
// 2: [XmlElement("B", Type = typeof(ChildB))]
// 3: [XmlArrayItem("A", Type = typeof(ChildA))]
// 3: [XmlArrayItem("B", Type = typeof(ChildB))]
public List<ChildClass> Data { get; set; }

// ... 序列化和反序列化代码在此处 ...</code>
Copy after login

Select the preferred method and uncomment the corresponding code snippet for serialization of derived classes.

The above is the detailed content of How to Serialize Derived Classes within Generic Lists using XmlSerializer?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template