C# - XmlIgnore不能使用override或new修饰符

时间:2016-06-02 13:46:16

标签: c# xmlserializer

[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

1 个答案:

答案 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);