我今天发现了一件让我很困惑的事情:
1. 如果我有这个:
public interface INamed
{
[XmlAttribute]
string Name { get; set; }
}
public class Named : INamed
{
public string Name { get; set; }
}
它给出以下输出(名称属性序列化为元素):
<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
成员“NamedDerived.Name”隐藏了继承的成员“NamedBase.Name”,但具有不同的自定义属性。
我用于序列化的代码:
[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 属性的正确方法是什么?