Xml-attributes in interfaces and abstract classes

半城伤御伤魂 提交于 2019-12-06 04:17:44

问题


I found something that confused me today:

1. If I have this:

public interface INamed
{
    [XmlAttribute]
    string Name { get; set; }
}

public class Named : INamed
{
    public string Name { get; set; }
}

It gives the following output (Name property serialized as element):

<Named>
  <Name>Johan</Name>
</Named>

2. If I have this:

public abstract class NamedBase
{
    [XmlAttribute]
    public abstract string Name { get; set; }
}

public class NamedDerived : NamedBase
{
    public override string Name { get; set; }
}

The XmlSerializer throws System.InvalidOperationException

Member 'NamedDerived.Name' hides inherited member 'NamedBase.Name', but has different custom attributes.

The code I used for serialization:

[TestFixture] 
public class XmlAttributeTest
{
    [Test]
    public void SerializeTest()
    {
        var named = new NamedDerived {Name = "Johan"};
        var xmlSerializer = new XmlSerializer(named.GetType());
        var stringBuilder = new StringBuilder();
        using (var stringWriter = new StringWriter(stringBuilder))
        {
            xmlSerializer.Serialize(stringWriter, named);
        }
        Console.WriteLine(stringBuilder.ToString());
    }
}

My question is:

Am I doing it wrong and if so what is the correct way to use xml attributes in interfaces and abstract classes?


回答1:


Attributes are not inherited on overriden properties. You need to redeclare them. Also in your first example the behavior is not the "expected" one as you declared XmlAttribute at the interface level and yet the serialized xml contains the value as an element. So the attribute in the interface is ignored and only info taken from the actual class matters.




回答2:


I think you should xmlignore your abstract class property

public abstract class NamedBase
{
    [XmlIgnore]
    public abstract string Name { get; set; }
}

public class NamedDerived : NamedBase
{
    [XmlAttribute]
    public override string Name { get; set; }
}


来源:https://stackoverflow.com/questions/13182420/xml-attributes-in-interfaces-and-abstract-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!