gpt4 book ai didi

c# - 如何强制对同名的派生类型进行 XML 反序列化?

转载 作者:行者123 更新时间:2023-11-30 17:59:32 24 4
gpt4 key购买 nike

我无法修改库中提供的类型,例如:

namespace BaseNamespace
{
public class A
{
public string Foo { get; set; }
}
}

我还有一个名为 SomeOtherNamespace.A"的类,它派生自 BaseNamespace.A,如下所示:

namespace SomeOtherNamespace
{
public class A : BaseNamespace.A
{
public string DoSomething() {}
}
}

我从网络服务中收到了一个 XML 负载。

我想反序列化 XML,以便最终得到一个 SomeOtherNamespace.A 对象。但是,当我运行以下代码时

string xml = "<A Foo=\"test\"></A>";

XmlSerializer serializer = new XmlSerializer(typeof(A));

StringReader reader = new StringReader(xml);

A obj = serializer.Deserialize(reader) as A;

我得到一个错误:

Types 'BaseNamespace.A' and 'SomeOtherNamespace.A' both use the XML type name, 'A', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.

问题:在不修改类 BaseNamespace.A 的情况下,如何强制反序列化到我的派生类型 SomeOtherNamespace.A?

最佳答案

将您的 SomeOtherNamespace.A 重命名为

namespace SomeOtherNamespace
{
public class AAA : BaseNamespace.A
{
public string DoSomething() {}
}

并创建序列化器为

XmlRootAttribute root = new XmlRootAttribute("A");
XmlSerializer serializer = new XmlSerializer(typeof(AAA),root);

关于c# - 如何强制对同名的派生类型进行 XML 反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11095443/

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