gpt4 book ai didi

c# - XmlSerializer 在枚举上抛出异常

转载 作者:太空宇宙 更新时间:2023-11-03 13:40:35 25 4
gpt4 key购买 nike

对于以下代码,XmlSerializer 会抛出一个预期,因为 Foo 包含两个与枚举 EnumSameName 同名的属性。

框架.NET 4.0

public class Bar1
{
public enum EnumSameName
{
a
}

public EnumSameName MyBar1Enum { get; set; }
}

public class Bar2
{
public enum EnumSameName
{
b
}

public EnumSameName MyBar2Enum { get; set; }
}

public class Foo
{
public Foo()
{
MyEnum1 = new Bar1();
MyEnum2 = new Bar2();
}

public Bar1 MyEnum1 { get; set; }

public Bar2 MyEnum2 { get; set; }
}

现在尝试序列化Foo

var parameter = new Foo();
var serializer = new XmlSerializer(parameter.GetType());
// ERROR System.InvalidOperationException: [...]

重命名 EnumSameName 之一后,一切都按预期工作。

这个错误从何而来?

最佳答案

有问题的错误信息应该是

Types 'Bar2.EnumSameName' and 'Bar1.EnumSameName' both use the XML type name, 'EnumSameName', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type.

看看

XML Namespace Collisions, XmlNodeList and Deserialization, and More

你可以尝试把代码改成

[XmlRoot("Bar1", Namespace = "http://example.com/schemas/Bar1")]
public class Bar1
{
[XmlRoot("Bar1EnumSameName", Namespace = "http://example.com/schemas/Bar1")]
public enum EnumSameName
{
a
}

public EnumSameName Mode { get; set; }
}

[XmlRoot("Bar2", Namespace = "http://example.com/schemas/Bar2")]
public class Bar2
{
[XmlRoot("Bar2EnumSameName", Namespace = "http://example.com/schemas/Bar2")]
public enum EnumSameName
{
b
}

public EnumSameName Mode { get; set; }
}

作为事后的想法,只需添加 XmlRoot documentation

Controls XML serialization of the attribute target as an XML root element.

关于c# - XmlSerializer 在枚举上抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17183676/

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