C# 序列化多态列表,但无法更改类型定义

C# 序列化多态列表,但无法更改类型定义,c#,serialization,C#,Serialization,我正在使用另一方的DLL,它定义了动物、猫、鱼类 //Begin another party's DLL public class animals { } public class cat : animals { public string size { get; set; } public string furColor { get; set; } } public class fish : animals { public string size { get; s

我正在使用另一方的DLL,它定义了动物、猫、鱼类

//Begin another party's DLL
public class animals
{
}

public class cat : animals
{
    public string size { get; set; }
    public string furColor { get; set; }
}

public class fish : animals
{
    public string size { get; set; }
    public string scaleColor { get; set; }
}
//End another party's DLL

static void Main(string[] args)
{

    using (var xmlWriter = XmlWriter.Create("a.xml", new XmlWriterSettings { Indent = true }))
    {
        var eventArgsList = new List<animals>();
        eventArgsList.Add(new cat { size = "10", furColor = "red" });
        eventArgsList.Add(new fish { size = "20", scaleColor = "blue" });

        new XmlSerializer(eventArgsList.GetType(),new[] { typeof(cat), typeof(fish) }).Serialize(xmlWriter, eventArgsList);
    }
}
//开始另一方的DLL
公营动物
{
}
公猫:动物
{
公共字符串大小{get;set;}
公共字符串furColor{get;set;}
}
公营鱼类:动物
{
公共字符串大小{get;set;}
公共字符串scaleColor{get;set;}
}
//结束另一方的DLL
静态void Main(字符串[]参数)
{
使用(var xmlWriter=xmlWriter.Create(“a.xml”,新的XmlWriterSettings{Indent=true}))
{

var eventArgsList=new List,但我无法更改类型定义。我想我必须使用
XmlAttributeOverrides
,有人能告诉我怎么做吗?

为了在XML中使用该结构而不必编写自定义序列化程序,您需要在C#类中使用相同的结构。但这很容易,因为Visual Studio可以做到这一点给你

复制所需的XML和。它将创建以下类。您需要进行一次调整并设置
AnonymousType=false
,如下所示

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = false)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Animals
{

    private AnimalsCat[] catField;

    private AnimalsFish[] fishField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("cat")]
    public AnimalsCat[] cat
    {
        get
        {
            return this.catField;
        }
        set
        {
            this.catField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("fish")]
    public AnimalsFish[] fish
    {
        get
        {
            return this.fishField;
        }
        set
        {
            this.fishField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = false)]
public partial class AnimalsCat
{

    private byte sizeField;

    private string furColorField;

    /// <remarks/>
    public byte size
    {
        get
        {
            return this.sizeField;
        }
        set
        {
            this.sizeField = value;
        }
    }

    /// <remarks/>
    public string furColor
    {
        get
        {
            return this.furColorField;
        }
        set
        {
            this.furColorField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = false)]
public partial class AnimalsFish
{

    private byte sizeField;

    private string scaleColorField;

    /// <remarks/>
    public byte size
    {
        get
        {
            return this.sizeField;
        }
        set
        {
            this.sizeField = value;
        }
    }

    /// <remarks/>
    public string scaleColor
    {
        get
        {
            return this.scaleColorField;
        }
        set
        {
            this.scaleColorField = value;
        }
    }
}
输出

<?xml version="1.0" encoding="utf-8"?>
<Animals xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <cat>
    <size>10</size>
    <furColor>red</furColor>
  </cat>
  <fish>
    <size>20</size>
    <scaleColor>blue</scaleColor>
  </fish>
  <fish>
    <size>30</size>
    <scaleColor>orange</scaleColor>
  </fish>
</Animals>

10
红色
20
蓝色
30
橙色

受CodingYoshi创新方法的启发,我发现下面的helper类缩短了100行

[XmlRoot("Animals")]
public class AnimalsHelper
{
    [XmlElement("Cat", typeof(cat))]
    [XmlElement("Fish", typeof(fish))]
    public List<animals> Animals { get; set; } = new List<animals>();
}

static void Main(string[] args)
{

    using (var xmlWriter = XmlWriter.Create("a.xml", new XmlWriterSettings { Indent = true }))
    {
        var animalsHelper= new AnimalsHelper();
        animalsHelper.Animals.Add(new cat { size = "10", furColor = "red" });
        animalsHelper.Animals.Add(new fish { size = "20", scaleColor = "blue" });

        new XmlSerializer(animalsHelper.GetType(),new[] { typeof(cat), typeof(fish) }).Serialize(xmlWriter, animalsHelper);
    }

    using (var xmlReader = XmlReader.Create("a.xml", new XmlReaderSettings { IgnoreWhitespace = true }))
    {
        var obj = (AnimalsHelper)new XmlSerializer(animalsHelper.GetType(), new[] { typeof(cat), typeof(fish) }).Deserialize(xmlReader);

    }
}
[XmlRoot(“动物”)]
公共类动物助手
{
[XmlElement(“Cat”,类型(Cat))]
[XmlElement(“鱼”,类型(鱼))]
public List-rands{get;set;}=newlist();
}
静态void Main(字符串[]参数)
{
使用(var xmlWriter=xmlWriter.Create(“a.xml”,新的XmlWriterSettings{Indent=true}))
{
var animalsHelper=新的animalsHelper();
AnimalHelper.Animals.Add(新猫{size=“10”,furColor=“red”});
animalsHelper.Animals.Add(新鱼{size=“20”,scaleColor=“blue”});
新的XmlSerializer(animalHelper.GetType(),new[]{typeof(cat),typeof(fish)});
}
使用(var xmlReader=xmlReader.Create(“a.xml”,新的XmlReaderSettings{IgnoreWhitespace=true}))
{
var obj=(animalHelper)新的XmlSerializer(animalHelper.GetType(),new[]{typeof(cat),typeof(fish)});
}
}

我仍然渴望一个不使用帮助类的解决方案。

你的方法很有创新性。你能解释一下为什么XmlAttributeOverrides在我的场景中没有帮助吗?@GQNBIG我从来没有说过它不会有帮助。这可能也行,但我发现这种方法更容易,因为工具(vs)有帮助。如果我不需要,为什么要编写代码?;)
[XmlRoot("Animals")]
public class AnimalsHelper
{
    [XmlElement("Cat", typeof(cat))]
    [XmlElement("Fish", typeof(fish))]
    public List<animals> Animals { get; set; } = new List<animals>();
}

static void Main(string[] args)
{

    using (var xmlWriter = XmlWriter.Create("a.xml", new XmlWriterSettings { Indent = true }))
    {
        var animalsHelper= new AnimalsHelper();
        animalsHelper.Animals.Add(new cat { size = "10", furColor = "red" });
        animalsHelper.Animals.Add(new fish { size = "20", scaleColor = "blue" });

        new XmlSerializer(animalsHelper.GetType(),new[] { typeof(cat), typeof(fish) }).Serialize(xmlWriter, animalsHelper);
    }

    using (var xmlReader = XmlReader.Create("a.xml", new XmlReaderSettings { IgnoreWhitespace = true }))
    {
        var obj = (AnimalsHelper)new XmlSerializer(animalsHelper.GetType(), new[] { typeof(cat), typeof(fish) }).Deserialize(xmlReader);

    }
}