[TestFixture]
public class XmlIgnoreWithNewModifierTest
{
public class Parent
{
public int Name { get; set; }
}
public class Child : Parent
{
[XmlIgnore]
public new int Name
{
get { throw new NotImplementedException(); }
}
}
[Test]
public void Test()
{
var serializer = new XmlSerializer(typeof(Child));
var stream = new MemoryStream();
// Throws
serializer.Serialize(stream, new Child());
}
}
最后一行代码会抛出InvalidOperationException
内部NotImplementedException
。使Parent.Name
虚拟和Child.Name
覆盖无效。
我想知道是否可以让XmlIgnore仅适用于Child.Name
但不适用于Parent.Name
?
答案 0 :(得分:0)
如本回答所述: Excluding some properties during serialization without changing the original class
您应该使用:
XmlAttributes attributes = new XmlAttributes { XmlIgnore = true };
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(Parent), "Name", attributes);
XmlSerializer serialize = new XmlSerializer(typeof(Child), overrides);