gpt4 book ai didi

c# - 如何在 Xml 中序列化派生类?

转载 作者:数据小太阳 更新时间:2023-10-29 02:47:53 26 4
gpt4 key购买 nike

想象这是我的场景:

public abstract class Foo
{
public abstract int X { get; set; }
}

public class FooA : Foo
{
public override int X { get; set; }
public int Y { get; set; }
}

public class FooB : Foo
{
public override int X { get; set; }
public int Z { get; set; }
}

这是一个服务,我有一些对象要序列化。

public class FooService
{
public List<Foo> GetModels()
{
return new List<Foo>()
{
new FooA() { X = 3, Y = 6 },
new FooB() { X = 5, Z = 10 }
};
}
}

这是我无法序列化我的对象的方法,它会抛出异常。我想序列化派生类。

    private void SerializeObjects()
{
FooService service = new FooService();
var a = service.GetModels();

XmlSerializer x = new XmlSerializer(a.GetType());
TextWriter writer = new StreamWriter("A.xml");

x.Serialize(writer, a);
writer.Close();
}

最佳答案

您必须将派生类型告诉序列化器

[XmlInclude(typeof(FooA))]
[XmlInclude(typeof(FooB))]
public abstract class Foo
{
public abstract int X { get; set; }
}

这是真正有用的 .Net 异常之一。如果您查看 InnerException,您将看到

The type FooA was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

更新

根据您对不同模块中许多派生类型的评论,您还可以在创建序列化程序时而不是在编译时在运行时指定派生类型:

How to add XmlInclude attribute dynamically

关于c# - 如何在 Xml 中序列化派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9830698/

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