gpt4 book ai didi

c# - XML 序列化具有抽象基类的可序列化对象的通用列表

转载 作者:太空狗 更新时间:2023-10-29 19:57:23 25 4
gpt4 key购买 nike

任何关于如何使用抽象基类序列化通用对象列表的好示例。 XML Serialize generic list of serializable objects 中列出了具有非抽象基类的示例.我的基类类似于 Microsoft.Build.Utilities.Task

最佳答案

另一种方法是使用 XmlElementAttribute 将已知类型列表移动到通用列表本身...

using System;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;

public abstract class Animal
{
public int Weight { get; set; }
}

public class Cat : Animal
{
public int FurLength { get; set; }
}

public class Fish : Animal
{
public int ScalesCount { get; set; }
}

public class AnimalFarm
{
[XmlElement(typeof(Cat))]
[XmlElement(typeof(Fish))]
public List<Animal> Animals { get; set; }

public AnimalFarm()
{
Animals = new List<Animal>();
}
}

public class Program
{
public static void Main()
{
AnimalFarm animalFarm = new AnimalFarm();
animalFarm.Animals.Add(new Cat() { Weight = 4000, FurLength = 3 });
animalFarm.Animals.Add(new Fish() { Weight = 200, ScalesCount = 99 });
XmlSerializer serializer = new XmlSerializer(typeof(AnimalFarm));
serializer.Serialize(Console.Out, animalFarm);
}
}

...这也将导致更好看的 XML 输出(没有丑陋的 xsi:type 属性)...

<?xml version="1.0" encoding="ibm850"?>
<AnimalFarm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Cat>
<Weight>4000</Weight>
<FurLength>3</FurLength>
</Cat>
<Fish>
<Weight>200</Weight>
<ScalesCount>99</ScalesCount>
</Fish>
</AnimalFarm>

关于c# - XML 序列化具有抽象基类的可序列化对象的通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9247017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com