接口和抽象类中的 Xml 属性 [英] Xml-attributes in interfaces and abstract classes

查看:44
本文介绍了接口和抽象类中的 Xml 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天发现了一些令我困惑的事情:

I found something that confused me today:

1.如果我有这个:

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.如果我有这个:

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

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

XmlSerializer 抛出 System.InvalidOperationException

The XmlSerializer throws System.InvalidOperationException

成员NamedDerived.Name"隐藏继承成员NamedBase.Name",但具有不同的自定义属性.

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

我用于序列化的代码:

[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());
    }
}

我的问题是:

我做错了吗?如果是,在接口和抽象类中使用 xml 属性的正确方法是什么?

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

推荐答案

属性不会在被覆盖的属性上继承.您需要重新声明它们.同样在您的第一个示例中,行为不是您在接口级别声明 XmlAttribute 时的预期"行为,但序列化的 xml 包含作为元素的值.所以接口中的属性被忽略,只有从实际类中获取的信息才重要.

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.

这篇关于接口和抽象类中的 Xml 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆